简体   繁体   中英

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

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]

You can simply loop over the other related model like so:

for product_gallery_image in product_instance.productgalleryimage_set.all():
    print(product_gallery_image.product_gallery_image)

The productgalleryimage_set here is simply the related model name in lowercase with _set appended. You can change this by setting the related_name attribute on the foreign key.
Note: This will perform a query to fetch each of the product_gallery_image objects of some product instance.

If you want to get the first object only:

product_gallery_image = product_instance.productgalleryimage_set.first()

If you want to perform a join as in your example which will perform only one query you can use select_related (this will only work in forward direction for reverse direction look at prefetch_related ):

product_gallery_images = ProductGalleryImage.objects.all().select_related('product')
for product_gallery_image in product_gallery_images:
    print(product_gallery_image.product.product_name)
    print(product_gallery_image.product_gallery_image)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM