在模板上使用 a 到 m2m 的附加字段

Using additional fields of a through m2m on template

我的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 %}

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

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

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

感谢帮助

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!它是用于访问 City:

Profile 个实例的相关经理的名称
city.user_city.all()  
# Bad: because this is a QuerySet of Profiles
# Better: related_name = 'users'