我在与ManyToManyField链接的模型中有几个类:
class UserProfile(models.Model):
contacts = models.ManyToManyField(Contact)
class Contact(models.Model):
first_name = models.CharField(max_length=50)
在一个视图中,我正在传递:
contacts_list = request.user_profile.contacts
这会产生一些奇怪的数字字符串,每次刷新模板时都会更改:
{% for c in contacts_list %}
{{ c }}
{% endfor %}
这不会产生任何结果:
{% for c in contacts_list %}
{{ c.first_name }}
{% endfor %}
在我的Contact类中,我还定义了__unicode__(self)
以返回first_name
,那么为什么ManyToManyField
对象不返回此值?我也无法弄清楚如何成功显示first_name
字段值。感谢您的任何建议或帮助!
答案 0 :(得分:4)
尝试添加all
进行查看:
contacts_list = request.user_profile.contacts.all()
或模板:
{% for c in contacts_list.all %}
{{ c.first_name }}
{% endfor %}