【问题标题】:Using additional fields of a through m2m on template在模板上使用 a 到 m2m 的附加字段
【发布时间】:2016-06-02 22:29:59
【问题描述】:

我的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 循环中找到合适的用户)。

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

感谢您的帮助

【问题讨论】:

    标签: python html django m2m


    【解决方案1】:

    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!它是用于访问CityProfile 实例的相关经理的名称:

    city.user_city.all()  
    # Bad: because this is a QuerySet of Profiles
    # Better: related_name = 'users'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      相关资源
      最近更新 更多