mortymacs
mortymacs

Reputation: 3736

access to joined models in django views and templates

for joining many models with each other, I did , for example :

Message.objects.filter(conversation__recipient__user=request.user)

when I want to use it in the template side , it doesn't show me anything. example:

{{row.conversation.recipient.user.username}}

this is my code:

model:

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)

view:

def admin_index(request):
    rows = Message.objects.filter(conversation__recipient__user=request.user)
    return render(request,'message/admin/index.html',{'rows':rows})

template:

{% 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 %}

So how can I get access to recipient models in views and templates via Message model?

Thanks

Upvotes: 0

Views: 100

Answers (1)

Rohan
Rohan

Reputation: 53366

As Recipient model has ForeignKey with Conversation model, there are many recipients for a conversation. So conversation objects will have receipient_set as queryset. You need to iterate over it and get either first/last or all objects to display.

So your template code needs to change as

{% 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%}

Upvotes: 2

Related Questions