[英]Django Querying chained Foreign Key
您好,我正在學習 Django ORM 查詢並找出外鍵中的反向關系。 我無法在外鍵字段中可視化 _set 希望我會在這里被清除。 這是我一直在工作的 model。
class Location(BaseModel):
name = models.CharField(
max_length=50,
validators=[validate_location_name],
unique=True,
)
我有 Route model 與 Location 作為 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
將外鍵與Route
鏈接
class BusCompanyRoute(BaseModel):
route = models.ForeignKey(Route, on_delete=models.PROTECT)
最后,我將Schedule
Model 與BusCompanyRoute
鏈接為Fk
class Schedule(BaseModel):
bus_company_route = models.ForeignKey(BusCompanyRoute, on_delete=models.PROTECT)
問題是我想從附表 model 上的視圖中查詢想要與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.objects.filter(bus_company_route__route__departure__name="A", bus_company_route__route__destination__name="B")
有關更多信息,請參閱如何在 Django 中進行查找。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.