Wonderfull
(ps :sorry, I should have put the model)

On Friday, May 20, 2016 at 2:40:33 AM UTC-4, James Schneider wrote:
>
> On Wed, May 18, 2016 at 9:54 PM, stunaz <stu...@gmail.com <javascript:>> 
> wrote:
>
>> Hi,
>> I would like to write the following query using django orm.
>>
>> select * ,
>> (select image_url from blog_image bi where bi.blog_id = b.id and bi.
>> principal=1) as blog_main_imange
>> from blog b
>>
>>
>> Any idea, how to write the queryset ?
>>
>
> Without Django models, not with much accuracy.
>
> Assuming that your models are named Blog and BlogImage, with an FK from 
> Blog to BlogImage named 'image', I think you can do something like this:
>
>
> from django.db.models import Prefetch
>
> Blog.objects.all().prefetch_related(
>     Prefetch('image', 
>              queryset=BlogImage.objects.filter(principal=1), 
>              to_attr='blog_main_image'
>             )
> )
>
>
> References:
>
>
> https://docs.djangoproject.com/en/1.9/ref/models/querysets/#prefetch-related
>
> https://docs.djangoproject.com/en/1.9/ref/models/querysets/#prefetch-objects
>
> Completely untested and written off the top of my head using a model 
> structure I deduced from your query, so YMMV, but I hope that at least 
> points you in the right direction.
>
> -James
>

-- 
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+unsubscr...@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/618cd7e7-af47-4268-bd5b-7b416b2131a9%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to