pythondjangodjango-modelsdjango-orm

How to query a reverse foreign key multiple times in Django ORM


Assuming the following models:

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)

How to create a queryset of all 'consignments' of all instances of a specific 'stores' queryset like so:

target_stores = Store.objects.filter(name__startswith="One")
consignments = target_stores.consignments.all()

Solution

  • You query in reverse by spanning over multiple relations with the __ separator:

    Consignment.objects.filter(order__stock__store__name__startswith='One')