我想在用户模型中显示用户的用户名,名字和姓氏,然后显示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 %}
但是,它显示一个用户拥有所有城市而不是匹配的城市。
像这样:来自Stolkholm的crystalgillespie Crystal Gillespie,
来自Stolkholm的crystalgillespie Crystal Gillespie,
来自圣保罗的crystalgillespie Crystal Gillespie,
来自巴黎的crystalgillespie Crystal Gillespie,
来自格拉斯哥的crystalgillespie Crystal Gillespie,
来自马德里的crystalgillespie Crystal Gillespie,
来自马德里的crystalgillespie Crystal Gillespie,
来自Stolkholm的crystalgillespie Crystal Gillespie,
来自格拉斯哥的crystalgillespie Crystal Gillespie,
来自马德里的crystalgillespie Crystal Gillespie,
来自巴黎的crystalgillespie Crystal Gillespie,
来自Stolkholm的crystalgillespie Crystal Gillespie,
来自格拉斯哥的crystalgillespie Crystal Gillespie,
来自马德里的crystalgillespie Crystal Gillespie,
来自慕尼黑的crystalgillespie Crystal Gillespie,
谢谢。
答案 0 :(得分:3)
在用户对象中,您可以使用user.userprofile
关注配置文件的外键,然后从那里使用user.userprofile.city
访问该城市。
以下是您要演示的模板的简化版本。
{% for user in users %}
{{ user.username }}
{{ user.userprofile.profilepic }}
{{ user.userprofile.city.name }}
{% endfor %}
请注意,这意味着您无需在视图中提取个人资料和城市。您可以使用select_related
来减少sql查询的数量:
def index(request):
user_list = User.objects.select_related()[:5]
context_dict = {"users": user_list}
return render(request, "index.html", context_dict)