[Django]-Django Model : How to combine the reverse access sets from two foreignkey fields?

1πŸ‘

βœ…

To retrieve a QuerySet you can make use of Q objects (see Complex lookups with Q objects).

from django.db.models import Q
results = Segment.objects.filter(Q(start=node_x) | Q(end=node_x))

To access that more quickly you can define it as a property:

from django.db import models
from django.db.models import Q

class Node(models.Model):
    name = models.CharField(max_length=16)

    @property
    def segments(self):
        return Segment.objects.filter(Q(start=self) | Q(end=self))

Now in your code you can retrieve the segments by accessing the property:

In [1]: print node_x.segments  # or print(node_x.segments) in Python 3
Out[1]: [<Segment: Segment object>, <Segment: Segment object>, ...]
πŸ‘€sthzg

1πŸ‘

I think you should either use

Segment.objects.filter(start=node_x) | Segment.objects.filter(end=node_x)

or

node_x.start_segments.all() | node_x.end_segments.all()
πŸ‘€RemcoGerlich

Leave a comment