2010-06-18 103 views
0

的,如果有一個像在我遇到的所有用戶,然後在用戶, 當前登錄Django的查詢篩選一組數據

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

查詢,我想顯示這些用戶的博客文章。使用查詢,如:

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

那隻能說明我與用戶的博客帖子的ID = 1(儘管在當前登錄的用戶實際上並沒有跟隨他)在模板 我有:

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

我在哪裏錯了?

回答

2

.filter()返回一個集合,而不是一個事件。因此,我想說的問題是,第二個查詢應

blog = New.objects.filter(created_by__in = following) 
+0

奇怪的是,它沒有輸出我想要的。我想要實現的查詢是這樣的:select * from new,follow where created_by = user or created_by =(select * from new where following = user) – dana 2010-06-18 16:51:07

+0

我不確定是否有sql的OR for django ORM ,所以我可能會回到使用兩個查詢。 – Almad 2010-06-19 14:36:13

+0

你可以通過使用django.db.models中的'Q'對象(請參閱我對我的回答的評論) – 2010-06-21 07:16:51

0

或者更簡單:

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

但是,這感覺很奇怪,我......你確定你的模型設計的?

+0

簡單地對'Dj'進行'OR'處理,我想'翻譯'這樣的查詢:select * from新的,遵循 其中CREATED_BY =用戶 或 CREATED_BY =(來自新的地方下面選擇* =用戶) – dana 2010-06-18 16:49:40

+0

所以也許你需要使用Django的「Q」的對象,允許進行「OR」查詢:從Django的 。 db.models import Q MyModel.objects.filter(Q(some_field = something)| Q(some_other_field = foobar)) – 2010-06-21 07:15:39