如何遍历Django中的User和UserProfile?

2024-03-28 23:57:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从用户模型中显示用户的用户名、名字和姓氏,然后从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 %}

但是,它会向一个用户显示所有城市,而不是匹配的城市。你知道吗

像这样:

crystalgillespie Crystal Gillespie from Stolkholm, ,

crystalgillespie Crystal Gillespie from Stolkholm, ,

crystalgillespie Crystal Gillespie from Sao Paulo, ,

crystalgillespie Crystal Gillespie from Paris, ,

crystalgillespie Crystal Gillespie from Glasgow, ,

crystalgillespie Crystal Gillespie from Madrid, ,

crystalgillespie Crystal Gillespie from Madrid, ,

crystalgillespie Crystal Gillespie from Stolkholm, ,

crystalgillespie Crystal Gillespie from Glasgow, ,

crystalgillespie Crystal Gillespie from Madrid, ,

crystalgillespie Crystal Gillespie from Paris, ,

crystalgillespie Crystal Gillespie from Stolkholm, ,

crystalgillespie Crystal Gillespie from Glasgow, ,

crystalgillespie Crystal Gillespie from Madrid, ,

crystalgillespie Crystal Gillespie from Munich, ,

谢谢你。你知道吗


Tags: namefromselfcityformodelsdeflist
1条回答
网友
1楼 · 发布于 2024-03-28 23:57:08

从用户对象,您可以跟随外键到带有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)

相关问题 更多 >