django manytomany对象的字段返回空

时间:2012-06-20 10:21:25

标签: python django django-models many-to-many

我在与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字段值。感谢您的任何建议或帮助!

1 个答案:

答案 0 :(得分:4)

尝试添加all进行查看:

contacts_list = request.user_profile.contacts.all()

或模板:

{% for c in contacts_list.all %}
    {{ c.first_name }}
{% endfor %}