在模板上使用through m2m的其他字段

时间:2016-06-02 22:29:59

标签: python html django m2m

我的models.py

class Profile(models.Model):
    name = models.CharField(max_length=32)
    gender = models.CharField(max_length=1, choices=(('m', 'male'),
        ('f', 'female')), default='m')
    addresses = models.ManyToManyField(City, 
        related_name='user_city', through='User_City')

class User_City(models.Model):
    user = models.ForeignKey(Profile)
    address = models.ForeignKey(City)
    phone = models.CharField(max_length=32)

    class Meta:
        unique_together = ("user", "address")

我的view.py

def user_profile(request, city):
    a=Profile.objects.filter(addresses=city)
    context_dict['lista'] = a
    ###first alternative:
    #b=User_City.objects.filter(user=request.user, address=city)
    #context_dict['lista_address'] = b
    ###second alternative:
    #for c in a:
        #b=User_City.objects.filter(user=c, address=city)
        #c.phone=b.phone
    #context_dict['lista_address'] = c

我的template.html

{% for user in lista %}
  {{ user.name }}
  {{ user.gender}}
  {{ user.phone }}
  #{{ user.addresses.phone }}
  #{{ user.addresses__phone }}
{% endfor %}

它读取了姓名和性别但不是电话...... 我尝试了很多解决方案,但无济于事。

我可以添加lista_address context_dict,但后来我不知道如何在模板中使用(我应该在for循环中找到合适的用户)。

我可以在视图中添加一些属性,但它不起作用(属性不存在)。

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

addresses是一个ManyToManyField,那么{{ user.addresses.phone }}(或其类似的)如何知道哪些地址(City个实例)在那里可以看到向上phone

直接在User_City个对象上循环,而不是Profiles

# view.py
a = city.user_city_set.all()  # all through instances of city
# a = User_City.objects.filter(address=city)

# template.html
{% for u_c in lista %}
  {{ u_c.user.name }}
  {{ u_c.user.gender}}
  {{ u_c.phone }}
{% endfor %}

还有一点:'user_city'非常糟糕related_name!它是用于访问Profile的{​​{1}}个实例的相关管理员名称:

City