left join without where condition

19 views
Skip to first unread message

pythonw...@gmail.com

unread,
Apr 26, 2019, 9:21:01 AM4/26/19
to Django users
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?


Matthew Pava

unread,
Apr 26, 2019, 9:47:20 AM4/26/19
to django...@googlegroups.com

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 %}

--
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...@googlegroups.com.
To post to this group, send email to django...@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.

chirag soni

unread,
Apr 26, 2019, 11:58:54 AM4/26/19
to django...@googlegroups.com
You are telling something which I know already. Please observe my question keenly I need reverse of what you told. I. e. 
Photo modal has Product as ForeignKey
class Photo:
           file=models.FileField() 
           product=models.ForeignKey() 
          

Matthew Pava

unread,
Apr 26, 2019, 12:25:13 PM4/26/19
to django...@googlegroups.com

Then use the reverse accessor:

https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward

Product.objects.select_related(‘photo_set’)

{% for photo in product.photo_set.all %}

            {{ photo }}

{% empty %}

            This product has no photos.

{% endfor %}

Reply all
Reply to author
Forward
0 new messages