Friday, April 26, 2019

RE: left join without where condition

Use select_related or just reference it in the template as an attribute.

https://docs.djangoproject.com/en/2.1/ref/models/querysets/#select-related

 

Product.objects.select_related('photo')

 

{% if product.photo %}

            …

{% endif %}

 

From: django-users@googlegroups.com [mailto:django-users@googlegroups.com] On Behalf Of pythonwebdjango@gmail.com
Sent: Friday, April 26, 2019 8:03 AM
To: Django users
Subject: left join without where condition

 

What exactly I need?

  I have 2 models Product and Photo(having ForeignKey relationship with Product). Now suppose I inserted 3 products in Product table. For the 3rd product I not inserted any photo in Photo table. I want to fetch all the Products along with Photos but for the 3rd product photo should come as null(or None) because I not inserted. why I am doing like this because for the product for which no photos are uploaded I can check in the template that if null or None is coming as a photo then show a default image referring it from the static folder. I know we can achieve it using left join but how to achieve it in Django style?

 

What I have tried?

q=Product.objects.all().filter(photo__isnull=True)

print(q.query)

SELECT "app_product"."id", "app_product"."name"  FROM "app_product" LEFT OUTER JOIN "app_photo" ON

("app_product"."id" = "app_photo"."product_id") WHERE "app_photo"."id" IS NOT NULL

 

If in the above query I remove the where clause my problem will be resolved?

So how to do that in a django way?

 

 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/c8c00d69-f136-4c65-a87b-8466bcb2d866%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment