为了加入很多模型,我做了,例如:
Message.objects.filter(conversation__recipient__user=request.user)
当我想在模板方面使用它时,它不会向我显示任何内容。例如:
{{row.conversation.recipient.user.username}}
这是我的代码:
模型:
class Conversation(models.Model):
user = models.ForeignKey(User)
def __unicode__(self):
return self.user
class Message(models.Model):
conversation = models.ForeignKey(Conversation)
title = models.CharField(max_length=50)
body = models.CharField(max_length=500)
parent = models.IntegerField(default=0)
created = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.title
class Recipient(models.Model):
user = models.ForeignKey(User)
conversation = models.ForeignKey(Conversation)
is_read = models.BooleanField(default=False)
视图:
def admin_index(request):
rows = Message.objects.filter(conversation__recipient__user=request.user)
return render(request,'message/admin/index.html',{'rows':rows})
模板:
{% for i in rows %}
{% if not i.conversation.recipient.is_read %}
<tr class="set_bold">
{% else %}
<tr>
{% endif %}
<td>name:{{i.conversation.recipient}}</td>
<td class="col-md-0"><input type="checkbox"></td>
<td class="col-md-2">{{i.conversation.user.username}}</td>
<td><a href="{% url 'messages_read' i.id %}">{{i.title}}</a></td>
<td>{{i.created|date:"y-m-d"}} <small>({{i.created|timesince}})</small></td>
</tr>
{% empty %}
<tr>
<td colspan="4">{% trans "dont have any message" %}</td>
</tr>
{% endfor %}
那么如何通过消息模型访问视图和模板中的收件人模型?
由于
答案 0 :(得分:2)
由于Recipient
模型的ForeignKey
型号为Conversation
,因此会话中有许多收件人。因此conversation
个对象将receipient_set
作为查询集。您需要迭代它并获得要显示的第一个/最后一个或所有对象。
因此,您的模板代码需要更改为
{% for i in rows %}
{%for recp in i.conversation.recipient_set.all %}
{# do something with each recipient object
{% if not recp.is_read %}
<tr class="set_bold">
{% else %}
<tr>
....
{%endfor%}
{%endfor%}