djangodjango-rest-frameworkdjango-ormdjango-mysql

Compare mutiple ids present in list of dictionaries with the ids of model django


How can i make an efficient django orm query, which will compare ids from the list of dictionaries with the ids as foreign key in other model, e.g i have two models

Product:

product_name=models.CharField(max_length=20)

ProductOrder:

order_status=models.BooleanField()
product=models.ForeignKey(Product,on_delete=models.CASCADE)

now i want extract every product which is present in product order.

in simple query i can do this way:

prod=ProductOrder.objects.all()
products=Product.objects.all()
for prod in prod:
  for products in products:
   if prod.product==products.id:
        # save product

Is there any way to get this through one query or more efficiently?


Solution

  • You can filter with:

    products = Product.objects.filter(productorder__isnull=False).distinct()

    Here products is a QuerySet of Products for which there is at least one related ProductOrder.

    This works because we make a LEFT OUTER JOIN on the ProductOrder table and then check if that ProductOrder is not NULL. We use .distinct() [Django-doc] to prevent retrieving a Product that many times as there are ProductOrders. Likely the Django ORM will notice the __isnull=False constraint, and optimize this to an INNER JOIN.