简体   繁体   中英

Return fields that are related to a model by a foreignkey

class SenderInfo(models.Model):
    #to create unique id numbers
    sender = models.CharField(max_length=15)
    id_number = models.IntegerField(blank=True, null=True)
class Messages(models.Model):
    message_sender = models.ForeignKey(SenderInfo, related_name='messages')
    message_body = models.TextField()

I want to just return all the messages for each instance of SenderInfo . So I can see all the messages a user has made. I know how to see the Senders of a particular message but what's the simplest method to achieve the opposite?

这将返回包含所有消息的查询集:

sender.messages_set.all()

You can do this way:

views.py

sender_infos = SenderInfo.objects.all()

HTML template

{% for sender_info in sender_infos %}
    {{sender_info.sender}}
    {{sender_info.id_number}}
    {% for message in  sender_info.messages_set.all %}
        {{message.message_sender}}
        {{message.message_body}}
    {% endfor %}
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM