Django查询链式外键

2024-04-19 17:46:12 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我正在学习Django ORM查询,来了解外键中的反向关系。我无法想象外键字段中的设置,希望我在这里被清除。这是我一直在工作的模型

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

我将路线模型与位置链接为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模型与BusCompanyRoute链接为Fk

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

问题是我想从计划中的视图查询模型想要链接到departuredestination我将如何做到这一点?到目前为止,我只在view.py上做了这件事

schedule = Schedule.objects.all()

我一直在查询链接的外键


Tags: name模型链接onmodelslocationprotectdelete
2条回答

您可以这样简单地尝试:

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

有关更多信息,请参见how you can follow lookup in Django

我继续你的代码,因为一切看起来都很好

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)

您不需要反向关系来查询日程中的出发地和目的地

反向关系及其用例的简单解释可以在here中找到

相关问题 更多 >