1

I have 2 models I use this models to show the avatar in comments.

django_comments:

user_id comment ..... 

myapp_profile

user_id image_path ...... 

Actually i´m doing a raw query with cursor.execute(), to get this data

 ------- ---------- ------- 'user_id' 'image_path' 'comment' ------- ---------- ------- 3 name.jpg test 

but i want to do in "django orm ways"

Any solution?

Thanks

2 Answers 2

5

Think about this: What will you get back? That wouldn't be an instance of either model, would it?

However, with the newer annotate() and F() features, you might be able to pull off something like:

Comment.objects.all().annotate(image_path=F('user__profile__image_path')) 

Of course, you could always just:

Comment.objects.all().select_related() 

and get image_path from x.user.get_profile().image_path

Sign up to request clarification or add additional context in comments.

3 Comments

Comment.objects.all().annotate(image_path=F('user__profile__image_path')) I seems a good solution, but there is a problema i'm using django 1.0 - Comment.objects.all().select_related() The only problem is that i want to do only one query. Thanks for your time
@ger So your choices are clear: upgrade to Django trunk for the ORM features you need, accept multiple queries, or use raw SQL as you are now.
I need this as well (and select_related() won't work because this is a many2many relationship, properly filtered to a single row). The above does't work: 'F' object has no attribute 'lookup'.
1

You're looking for the feature suggested in ticket #14030, which will make the following work:

Comment.objects.all().annotate(image_path=F('user__profile__image_path')) 

What I am currently using:

Comment.objects.all().extra(select={'image_path': 'profiletable.image_path'}) 

Comments