Django 查询链式外键
Django Querying chained Foreign Key
你好,我正在学习 Django ORM 查询,想弄清楚外键中的反向关系。我无法想象外键字段中的 _set 希望我能在这里被清除。这是我一直在工作的模型。
class Location(BaseModel):
name = models.CharField(
max_length=50,
validators=[validate_location_name],
unique=True,
)
我有路线模型 linked 与位置作为 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'
)
同样,我有 Bus Company Route
linked 外键 Route
class BusCompanyRoute(BaseModel):
route = models.ForeignKey(Route, on_delete=models.PROTECT)
最后我 Schedule
模型 link 与 BusCompanyRoute
编辑为 Fk
class Schedule(BaseModel):
bus_company_route = models.ForeignKey(BusCompanyRoute, on_delete=models.PROTECT)
问题是我想从 Schedule 模型上的视图查询 link 和 departure
和 destination
我该怎么做?到目前为止,我只在 view.py
上这样做过
schedule = Schedule.objects.all()
我卡在查询链式外键上
我正在继续你的代码,因为一切看起来都很好
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)
您不需要从 Schedule 查询出发地和目的地的反向关系
可以找到反向关系及其用例的简单解释 here
您可以这样简单地尝试:
Schedule.objects.filter(bus_company_route__route__departure__name="A", bus_company_route__route__destination__name="B")
更多信息,请参阅how you can follow lookup in Django。
你好,我正在学习 Django ORM 查询,想弄清楚外键中的反向关系。我无法想象外键字段中的 _set 希望我能在这里被清除。这是我一直在工作的模型。
class Location(BaseModel):
name = models.CharField(
max_length=50,
validators=[validate_location_name],
unique=True,
)
我有路线模型 linked 与位置作为 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'
)
同样,我有 Bus Company Route
linked 外键 Route
class BusCompanyRoute(BaseModel):
route = models.ForeignKey(Route, on_delete=models.PROTECT)
最后我 Schedule
模型 link 与 BusCompanyRoute
编辑为 Fk
class Schedule(BaseModel):
bus_company_route = models.ForeignKey(BusCompanyRoute, on_delete=models.PROTECT)
问题是我想从 Schedule 模型上的视图查询 link 和 departure
和 destination
我该怎么做?到目前为止,我只在 view.py
schedule = Schedule.objects.all()
我卡在查询链式外键上
我正在继续你的代码,因为一切看起来都很好
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)
您不需要从 Schedule 查询出发地和目的地的反向关系
可以找到反向关系及其用例的简单解释 here
您可以这样简单地尝试:
Schedule.objects.filter(bus_company_route__route__departure__name="A", bus_company_route__route__destination__name="B")
更多信息,请参阅how you can follow lookup in Django。