假设以下模型:
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()
您可以通过使用
__
分隔符跨越多个关系来进行反向查询:
Consignment.objects.filter(order__stock__store__name__startswith='One')