[英]django manytomany object's field returns empty
在與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
字段值。 感謝您的任何建議或幫助!
嘗試添加all
視圖:
contacts_list = request.user_profile.contacts.all()
或模板:
{% for c in contacts_list.all %}
{{ c.first_name }}
{% endfor %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.