如何根据与其关联的模型的属性拉取User对象?

时间:2016-03-11 08:52:53

标签: django django-models django-views

我的模板会生成以下网址:/user/username,例如:/user/tainawilkins

<a href="user/{{ user.userprofile.slug }}"
style="color:rgba(0,0,200,1.00)">{{ user.username }} {{ user.first_name }} {{ user.last_name }}</a>

并调用此视图:

def user(request, user_name_slug):

    context_dict = {}

    try:
        # Can we find a city name slug with the given name?
        # If we can't, the .get() method raises a DoesNotExist exception.
        # So the .get() method returns one model instance or raises an exception.
        user = User.objects.select_related('UserProfile').get(slug=user_name_slug)
        context_dict['user_username'] = user.username
        context_dict['user_firstname'] = user.first_name
        context_dict['user_secondname'] = user.second_name

        context_dict['user'] = user
    except User.DoesNotExist:
        pass

    # Go render the response and return it to the client.
    return render(request, 'user.html', context_dict)

User模型是django内置模型,这是UserProfile:

# 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):
        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 UserProfile.userrating_set.all().aggregate(Avg('rating'))['rating__avg']

我的主要问题是在views.py中的这一行,我无法让它工作。我想通过指定UserProfile的slug(一对一关系)来拉取用户:

    user = User.objects.select_related('UserProfile').get(slug=user_name_slug)

我收到此错误:

   / user / tainawilkins中的FieldError无法将关键字'slug'解析为   领域。选项包括:date_joined,email,first_name,groups,hobby,id,   is_active,is_staff,is_superuser,language,last_login,last_name,   logentry,密码,registrationprofile,user_permissions,username,   userprofile,用户

1 个答案:

答案 0 :(得分:2)

一般情况下,我建议明确向related_name提供OneToOneField,例如:user = models.OneToOneField(User, related_name='profile')。如果没有它,默认情况下,相关名称为userprofile,您可以从错误消息中看到。

您可以使用<related_field_name>__<field_name_on_related_lookup>字段查找语法查询它,即:

user = User.objects.select_related('UserProfile').get(profile__slug=user_name_slug)

Lookups that span relationships

了解详情