Python 如何遍历django中的User和UserProfile?

Python 如何遍历django中的User和UserProfile?,python,django,models,Python,Django,Models,我想从用户模型中显示用户的用户名、名字和姓氏,然后从UserProfile中显示匹配的城市和国家 这些是模型: # this is the model for city class City(models.Model): name = models.CharField(max_length=128, default="", unique=True) country = models.CharField(max_length=128, default="Scotland")

我想从用户模型中显示用户的用户名、名字和姓氏,然后从UserProfile中显示匹配的城市和国家

这些是模型:

# this is the model for city
class City(models.Model):
    name = models.CharField(max_length=128, default="", unique=True)
    country = models.CharField(max_length=128, default="Scotland")
    slug = models.SlugField(unique=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(City, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.name

# this is model for user
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    profilepic = models.ImageField(blank=True)

    city = models.ForeignKey(City)
    slug = models.SlugField(unique=True)


    def save(self, *args, **kwargs):
        # Uncomment if you don't want the slug to change every time the name changes
        self.slug = slugify(self.user.username)
        super(UserProfile, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.user.username

    @property
    def avg_rating(User):
        return self.userrating_set.all().aggregate(Avg('rating'))['rating__avg']
这是一种观点:

def index(request):
    user_list = User.objects.order_by('-userrating')[:5]
    user_profile_list = UserProfile.objects.all()
    city_list = City.objects.order_by('-name')[:5]

    context_dict = {"users": user_list, "cities" : city_list, "profiles" : user_profile_list}

    return render(request, "index.html", context_dict)
这是一个模板:

            {% if users %}
                <ul>
                    {% for user in users %}
                    {% for profile in profiles %}

                        <li><p><a href="user/{{ user.slug }}"
                                  style="color:rgba(0,0,200,1.00)">{{ user.username }} {{ user.first_name }} {{ user.last_name }}</a>
                            from <a href="city/{{ user.city.slug }}"
                                    style="color:rgba(0,0,200,1.00)">{{ profile.city.name }}</a>, {{ user.city.country }}, {{ user.avg_rating }}
                        </p></li>

                    {% endfor %}
                    {% endfor %}
{%if用户%}
    {users%%中的用户为%s} {配置文件%中的配置文件为%1}
  • 从,{user.city.country},{{user.avg_rating}

  • {%endfor%} {%endfor%}
但是,它显示一个用户拥有所有城市,而不是匹配的城市

像这样:

Crystal Gillespie Stolkholm的Crystal Gillespie

Crystal Gillespie Stolkholm的Crystal Gillespie

Crystal Gillespie来自圣保罗的Crystal Gillespie

Crystal Gillespie来自巴黎的Crystal Gillespie

Crystal Gillespie来自格拉斯哥的Crystal Gillespie

Crystal Gillespie Crystal Gillespie来自马德里

Crystal Gillespie Crystal Gillespie来自马德里

Crystal Gillespie Stolkholm的Crystal Gillespie

Crystal Gillespie来自格拉斯哥的Crystal Gillespie

Crystal Gillespie Crystal Gillespie来自马德里

Crystal Gillespie来自巴黎的Crystal Gillespie

Crystal Gillespie Stolkholm的Crystal Gillespie

Crystal Gillespie来自格拉斯哥的Crystal Gillespie

Crystal Gillespie Crystal Gillespie来自马德里

Crystal Gillespie来自慕尼黑的Crystal Gillespie


谢谢。

从用户对象,您可以通过
user.userprofile
按照外键进入配置文件,然后通过
user.userprofile.city
进入城市

下面是要演示的模板的简化版本

{% for user in users %}
    {{ user.username }}
    {{ user.userprofile.profilepic }}
    {{ user.userprofile.city.name }}
{% endfor %}
请注意,这意味着您不需要在视图中获取配置文件和城市。您可以使用减少sql查询的数量:

def index(request):
    user_list = User.objects.select_related()[:5]
    context_dict = {"users": user_list}
    return render(request, "index.html", context_dict)

当我使用诸如:user.userprofile.city.name之类的东西时,它不起作用。它只是显示为空,即使我的数据库在每个用户配置文件中都包含城市。我不确定问题出在哪里。可能您正在通过没有用户配置文件的用户进行循环。很抱歉,我的数据有问题。你所有的解决方案都非常有效。谢谢