Search code examples
pythonmysqldjangodjango-filter

django filter get parent to child


i am using django(3.1.5). and i am trying to get parent model to child model by filter query i have model like -

class Product(models.Model):
   product_name = models.CharField(max_length=255, unique=True)
   is_feature = models.BooleanField(default=False)
   is_approved = models.BooleanField(default=False)
   created_at = models.DateTimeField(auto_now_add=True)

class ProductGalleryImage(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    product_gallery_image = models.FileField(upload_to='path')
    is_feature = models.BooleanField(default=False)

i am getting data from SELECT * FROM products_product AS pp INNER JOIN products_productgalleryimage AS ppgi ON ppgi.product_id = pp.id WHERE ppgi.is_feature=1 AND pp.is_feature=1 AND is_approved=1 ORDER BY pp.created_at LIMIT 4 mysql query.

so how can i get data like this query in django filter query


Solution

  • Firstly you can add related_name to ProductGalleryImage for better query support like this

    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_images')
    

    Then your query should be like this

    products=Product.objects.filter(is_approved=True, is_feature=True, product_images__is_feature=True).order_by('created_at')[:4]