2015-05-05 19 views
0

我希望,我正確地題寫了書名...)))獲取所有的型號列表,即當前的用戶連接到

我有模式article,可以通過ManyToMany域連接到用戶。

from django.db import models 
from django.contrib.auth.models import User 
from django.db import models 

class Article(models.Model): 
    class Meta(): 
     db_table = 'article' 

    article_users = models.ManyToManyField(User, null=True, blank=True, default=None) 
    article_title = models.CharField(max_length=200, blank=False, null=False) 
    article_content = models.IntegerField(choices=CONTENT_CHOICES, null=True, blank=True) 

而且我可以列出所有用戶,誰通過連接到該模型模板:

{% for user in article.article_users.all %} 
    {{ user.username }} 
{% endfor %} 

但我怎麼能列出所有的車型,以它目前的用戶連接到?

回答

1

是你在找什麼?

{% for article in user.article_set.all() %} 
    {{article.article_title}} 
{% endfor %} 

也許你會需要防止這種代碼,如果用戶是匿名:

{% if user.is_authenticated() %} 
    {% for article in user.article_set.all() %} 
     {{article.article_title}} 
    {% endfor %} 
{% else %} 
    # Do something for anonymous users. 
{% endif %} 

編輯:更換request.user與用戶

+0

是的,這實際上是我需要什麼。我又忘了'_set' ...:/非常感謝。 P.S .:沒有'請求'方法需要,只要我嘗試。只是'user.article_set.all'。視圖中需要請求和括號... –

+0

@spirit:確實,模板標籤中不需要請求。如果我的回答是您要查找的內容,請點擊綠色支票將其設置爲已接受。 –

相關問題