gpt4 book ai didi

django - 如何在 Django 中从多对多关系中检索数据

转载 作者:行者123 更新时间:2023-12-02 08:33:08 25 4
gpt4 key购买 nike

我有两个这样的模型:

class GuestStatus(models.Model):
guest_status = models.CharField(max_length=200)
arrangement = models.IntegerField(unique=True, help_text="Start from 1. Guest status will be arranged alphabetically.")

class Guest(models.Model):

user = models.ForeignKey(User)
full_name = models.CharField(max_length=250)
street_address = models.CharField(max_length=250, blank=True, null=True)
city = models.CharField(max_length=150, blank=True, null=True)
state = models.CharField(max_length=120, blank=True, null=True)
zip_code = models.CharField(max_length=15, blank=True, null=True)

status = models.ManyToManyField(GuestStatus, blank=True, null=True)
invitation_date = models.DateTimeField(blank=True, null=True)

我正在尝试检索模板中的数据:

#Views.py:
guests = Guest.objects.filter(user_id=request.user.id)

# Template:
{% for guest in guests %}
<tr>
<td width="5%"><input type="checkbox" value="{{ guest.id }}" name="guest_name" id="{{ forloop.counter }}" /></td>
<td><a href="/{{ guest.id }}/guest/">{{ guest.full_name }}</td>
<td>{{ guest.guests }}</td>
<td>{{ guest.children }}</td>
<td>{% for i in guest.gueststatus_set.all %}{{ i.status }}{% endfor %}</td>

</tr>
{% endfor %}

这没有给出 gueststatus 的任何结果。怎么了?

最佳答案

对于ManyToMany,您没有得到_set,请将查询更改为guest.status.all(),也使用 {{i.guest_status}} 作为 GuestStatus 具有 guest_status 而不是 status

<td>{% for i in guest.status.all %}{{ i.status }}{% endfor %}</td>

关于django - 如何在 Django 中从多对多关系中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19700881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com