Search code examples
djangodjango-databasedjango-request

How to filter objects at django based on related field?


I have models:

  • Product
  • Store
  • ProductStore (additional table with foreign keys to Store and Product, also Boolean 'enabled', and stock(integer) )

The questions:

How can I filter Products which has Enabled=True for current store__id (from request)? Also, how can I add an additional field for every objects with stock at current store?

UPDATED:

class Product(models.Model): 
   pass 
class Store(models.Model):
   pass
class ProductStoreInfo(models.Model):
   enabled = models.BooleanField(default=True)
   product = models.ForeignKey(Product, related_name='stock_info', on_delete=models.CASCADE)
   store = models.ForeignKey(Store, related_name="stock", on_delete=models.CASCADE)
   stock = models.IntegerField(verbose_name=_('Stock'), blank=True, null=True, default=0, max_length=255)
   price = models.FloatField(verbose_name=_('Price'), blank=True, null=True, max_length=255)

Solution

  • You can filter this with:

    Product.objects.filter(
        stock_info__enabled=True
        stock_info__store_id=my_store_id
    )

    This will thus return a QuerySet that contains only Products for which there is a related ProductStoreInfo for which enabled is True and the store_id is the my_store_id (to be replaced with an expression that results in such id).

    We can also annotate our queryset with the stock data, like:

    from django.db.models import F, Min
    
    Product.objects.filter(
        stock_info__enabled=True
        stock_info__store_id=my_store_id
    ).annotate(
        stock=Min(F('store_info__stock'))
    )

    Here the Product objects from the queryset will have an extra attribute .stock that contains the stock column of the relevant ProductStore object (that satisfies the filtering).