Rahul Sharma
Rahul Sharma

Reputation: 2495

query a manytomany realted field

I have a model like the following:

GRN Model:

class GrnItems(models.Model):
    item = models.ForeignKey(Product, on_delete=models.CASCADE)
    item_quantity = models.IntegerField(default=0)
    item_price = models.IntegerField(default=0)
    label_name = models.CharField(max_length=25, blank=True, null=True)


class Grn(models.Model):

    reference_no = models.CharField(max_length=500, default=0)
    inward_date = models.DateTimeField(blank=True, null=True)
    items = models.ManyToManyField(GrnItems)

How can I query the GrnItems to get item_quantity which has product = 5 and connected to grn = 103?

Upvotes: 1

Views: 24

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477854

You can filter with:

GrnItems.objects.filter(item_id=5, grn__pk=103)

Here the grn will query the ManyToManyField in reverse.

Upvotes: 4

Related Questions