views:

33

answers:

2

if a have a query like

    following = Relations.objects.filter(initiated_by = request.user)

in which i'm having all the users followed by the currently logged in user, and i want to display those user's blog posts. Using a query like:

    blog = New.objects.filter(created_by = following)

it only shows me the blog posts of the user with the id = 1 (though the currently logged in user doesn't actually follow him) in template i have :

{% for object in blog %}
<a href='/accounts/profile_view/{{object.created_by}}/'> {{object.created_by}}</a> <br /> 
{{object.post}}<br />
{% endfor %}

Where am i wrong?

+1  A: 

.filter() returns a collection, not an occurence. Thus, I'd say problem is that second query should be

blog = New.objects.filter(created_by__in = following)
Almad
strangely, it did not output what i want. the query i want to achieve is something like: select * from new,follow where created_by = user or created_by = (select * from new where following = user)
dana
I'm not sure if there is sql's OR for django ORM, so I'd probably fall back to using two queries.
Almad
You can do 'OR' with Django by using the 'Q' object that is in django.db.models (see my comment on my answer)
Ghislain Leveque
A: 

Or even simpler :

bloc = New.objects.filter(created_by__initiated_by = request.user)

But that feels strange to me... are you sure of your model design ?

Ghislain Leveque
in brief, i want to 'translate' a query like that: select * from new,follow where created_by = user or created_by = (select * from new where following = user)
dana
so maybe you need to use the django 'Q' object which allows to make 'OR' queries : from django.db.models import Q MyModel.objects.filter(Q(some_field = something) | Q(some_other_field = foobar))
Ghislain Leveque