【问题标题】:How do I pull a User object based on the attribute of a model it is associated with?如何根据关联模型的属性拉取用户对象?
【发布时间】:2016-06-26 10:31:50
【问题描述】:

我的模板生成的 URL 是:/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, 语言, last_login, last_name, 登录,密码,registrationprofile,user_permissions,用户名, 用户资料,用户评分

【问题讨论】:

    标签: django django-models django-views


    【解决方案1】:

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

    您可以使用&lt;related_field_name&gt;__&lt;field_name_on_related_lookup&gt;字段查找语法来查询它,即:

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

    通过Lookups that span relationships了解更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-11
      • 2011-06-07
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多