0

Hello I am learning Django ORM queries and come to figure out reverse relationship in Foreign Key. I cannot visualize _set in foreign key field hope I will be cleared here. Here are my model I have been working.

class Location(BaseModel):
    name = models.CharField(
        max_length=50,
        validators=[validate_location_name],
        unique=True,
    )

I have Route model linked with Location as FK:

class Route(BaseModel):
    departure = models.ForeignKey(
        Location,
        on_delete=models.PROTECT,
        related_name='route_departure'
    )
    destination = models.ForeignKey(
        Location,
        on_delete=models.PROTECT,
        related_name='route_destination'
    )

Similarly I have Bus Company Route linked Foreign key with Route

class BusCompanyRoute(BaseModel):
    route = models.ForeignKey(Route, on_delete=models.PROTECT)

Finally I have Schedule Model linked with BusCompanyRoute as Fk

class Schedule(BaseModel):
    bus_company_route = models.ForeignKey(BusCompanyRoute, on_delete=models.PROTECT)

Problem is I want to query from views being on Schedule model want to link with departure and destination how will I do that? I have only done this so far on view.py

schedule = Schedule.objects.all()

I am stuck on querying Chained foreign key

lord stock
  • 1,191
  • 5
  • 32

2 Answers2

2

You can simply try like this:

Schedule.objects.filter(bus_company_route__route__departure__name="A", bus_company_route__route__destination__name="B")

For more information, please see how you can follow lookup in Django.

ruddra
  • 50,746
  • 7
  • 78
  • 101
  • one query: all foreign key above were one to many so that is reason we applied `bus_company_route__route__departure__name ='A'` ? PS: can you help me linking documentation for this concept. – lord stock Jan 07 '21 at 06:07
  • 1
    Sure. Documentation link: https://docs.djangoproject.com/en/3.1/topics/db/queries/#lookups-that-span-relationships – ruddra Jan 07 '21 at 06:19
1

I am continuing from your code, as everything looks fine

schedule = Schedule.objects.all()

for s in schedule:
    current_schedule_route = s.bus_company_route.route
    departure = current_schedule_route.destination.name
    destination = current_schedule_route.destination.name
    print(departure, '->', destination)

you don't need reverse relation to query departure and destination from Schedule

an easy explaination of reverse relation along with its use case can be found here

Hemant
  • 1,127
  • 1
  • 10
  • 18