如何在 Django ORM 中多次查询反向外键

问题描述 投票:0回答:1

假设以下模型:

class Store(models.Model):
    name = models.CharField(max_length=255)


class Stock(models.Model):
    name = models.CharField(max_length=255)
    store = models.ForeignKey(Store, on_delete=models.PROTECT)


class Consignment(models.Model):
    cost = models.FloatField()


class Order(models.Model):
    quantity = models.IntegerField()
    stock = models.ForeignKey(Stock, on_delete=models.PROTECT)
    consignment = models.ForeignKey(Consignment, on_delete=models.PROTECT)

如何创建特定“商店”查询集的所有实例的所有“托运”的查询集,如下所示:

target_stores = Store.objects.filter(name__startswith="One")
consignments = target_stores.consignments.all()
python django django-models django-orm
1个回答
0
投票

您可以通过使用

__
分隔符跨越多个关系来进行反向查询:

Consignment.objects.filter(order__stock__store__name__startswith='One')
© www.soinside.com 2019 - 2024. All rights reserved.