1

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()
1
  • So when is a Consignment related to a store, if there is an Order that links to a Stock that links to such Store? Commented Dec 6, 2024 at 12:52

1 Answer 1

1

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

Consignment.objects.filter(order__stock__store__name__startswith='One')
Sign up to request clarification or add additional context in comments.

2 Comments

I tried this solution but i got FieldError: Cannot resolve keyword 'order' into field. Choices are: cost, orders
@AhmedAshraf: that's because you specified a related_name='orders', so then it is orders__ instead of order__.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.