2015-12-17 45 views
0

我有這樣的查詢集:如何在渲染之前向查詢集結果添加額外的參數?

topics = Topic.objects.select_related('creator').filter(forum=forum_id).order_by("-created") 

我想添加到每個話題,rendring到模板,一個額外的布爾字段is_unread,這是基於另一個模型視圖計算之前。該字段不在主題模型中,應分別在視圖中爲每個request.user計算。

業務邏輯的僞代碼是這樣的:

for topic in topics: 
    if topic.lastposted > request.user.lastvisit.thistopic: 
     topic.is_unread = True 

包含lastvist是這樣的模式:

class LastVisitedTopic(models.Model): 
    user = models.ForeignKey(User) 
    forum = models.ForeignKey(Forum) 
    topic = models.ForeignKey(Topic) 
    lastvisited = models.DateTimeField(auto_now=True) 

當我打印出來topics它提供了一堆的對象:

[<Topic: Topic object>, <Topic: Topic object>, <Topic: Topic object>, '...(remaining elements truncated)...'] 

所以我不知道如何將is_unread追加到t下襬。所以感謝您的提示..

+1

沒有你的代碼的工作? –

+0

你的Django版本是什麼? – Gocht

+0

@Gocht django 1.8 – supermario

回答

1

你的方式應該是工作,但它有點難以管理。你應該在你的Topic類創建一個屬性的方法,而是把它叫做:

class Topic(models.Model): 
    # some fields go there 
    @property 
    def is_unread(self): 
     if self.last_posted > self.visitor.lasthit: 
      return True 
     else: 
      return False 

然後,當你做topic.is_unread沒有括號它將返回所需的值。

Python doc

編輯

聽起來OP沒有所有的參數駐留在Topic模型。在這種情況下,回落到原來的實現:

for topic in topics: 
    if topic.lastposted > request.user.lastvisit.thistopic: 
     topic.is_unread = True 
    else: 
     topic.is_unread = False 

在模板中,你可以這樣做:

{% for topic in topics %} 
    {{ topic.is_unread }} 
{% endfor %} 
+0

那麼問題是我在主題字段中沒有「訪客」字段。我剛纔提到的'visitor'實際上只是'request.user'誰獲取頁面。 – supermario

+0

你的代碼並不反映這一點。你有'topic.visitor',這意味着它是'topic'上的一個字段。我將編輯我的答案以涵蓋該內容,但是您還應該編輯代碼以減少混淆。 –

+0

對不起,我剛編輯我的僞代碼 – supermario

相關問題