how to filter field values based on other field id of same model in Django

Viewed 522

Here i want to filter the all the items of each group

let us consider my model as

class ItemsList(models.Model):
   invoice_number = models.IntegerField(blank=True, null=True)

class ItemsInvoice(models.Model):
    items = models.ForeignKey(ItemsList)

class StockItems(models.Model):
     item_invoice = models.ForeignKey(ItemsInvoice, blank=True, null=True)
     group_id = models.IntegerField(blank=True, null=True)

For example let us consider my database values as:

item_invoice    |    group_id
 
 2206           |   1
 2207           |   1
 2208           |   2
 2209           |   3
 2210           |   4
 2211           |   4
 2212           |   4
 2213           |   5

Now how can i write my filter statement based on group_id filter item_invoice and based on this item_invoice id's filter the items and based on these items ids filter invoice_number

1 Answers

Yo can filter the ItemInvoices by filtering on the group_id of the related StockItems:

ItemsInvoice.objects.filter(stockitems__group_id=my_group_id).distinct()

where my_group_id is the group_id for which we are looking. If there are multiple StockItems objects that link to the same ItemsInvoice and group_id, then we will retrieve only one instance for each ItemsInvoice due to the .distinct() [Django-doc] call.

Related