【问题标题】:"self.fields['field_name'].queryset" in Djano, can it be applied to a OneToOne field?Django中的“self.fields['field_name'].queryset”,可以应用于OneToOne字段吗?
【发布时间】:2022-01-11 15:48:57
【问题描述】:

我是 Django 新手,我一直在尝试用 _set.all() 解决 OneToOne 字段关系

我的模型.py

class User(AbstractUser):
    is_admin = models.BooleanField(default=False)
    is_employee = models.BooleanField(default=True)
    is_manager = models.BooleanField(default=False)
    is_assistant = models.BooleanField(default=False)


class Profile(models.Model):
    profile = models.OneToOneField(User, on_delete=models.CASCADE)


class Manager(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    user_profile = models.OneToOneField(Profile, on_delete=models.CASCADE)

我正在尝试更新 Manager 实例,但不太清楚为什么 self.instance.user.profile_set.all() 在本节中不断抛出“'User' object has no attribute 'profile_set'”AttributeError:

forms.py

elif self.instance.pk:
        self.fields['user_profile'].queryset = self.instance.user.profile_set.all()

我希望我的问题很清楚,任何帮助将不胜感激! 干杯!

【问题讨论】:

  • 它是self.instance.user.profile
  • 你真的应该重新考虑你的设计。 Manager 模型是非常不必要的。您已经知道用户是否是经理。并且配置文件用户字段应称为用户而不是配置文件以避免问题

标签: django set django-queryset


【解决方案1】:

您可以通过以下方式访问User 的相关Profile

<em>myuser</em>.<strong>profile</strong>

确实,OneToOneField 本质上是带有unique=True 约束的ForeignKey。这意味着对于User至多有一个相关的Profilerelated_name=… parameter [Django-doc] 默认是小写的类名(这里是Profile)(所以profile)。因此,您可以使用.profile 访问相关的Profile。如果不存在这样的Profile,它将引发AttributeError

但是manager的建模有冗余数据:UserProfile不需要都指定,可以先确定另一个。通过引入重复数据,您可以在将来Managers 存在user 更新但user_profile 不存在的位置,反之亦然。如果您需要profile 并且您存储了user,您可以使用<i>mymanager</i><b>.user.profile</b> 访问它,如果您存储了user_profile,您可以使用<i>mymanager</i><b>.user_profile.user</b> 访问它。因此,存储两者没有多大意义。


注意:通常使用settings.AUTH_USER_MODEL [Django-doc] 引用用户模型比直接使用User model [Django-doc] 更好。更多信息可以查看referencing the User model section of the documentation

【讨论】:

  • 我尝试了 self.fields['user_profile'].queryset = self.instance.user.profile 但仍然出现 AttributeError,''Profile' 对象没有属性 'all''(不确定在哪里'all' 来自这里)。感谢您让我知道在哪里可以改进 db,不胜感激!
  • 我尝试追溯...... a = self.instance.user.profile 给了我正确的用户配置文件,但是当我做了 self.fields['user_profile'].queryset =给了我“AttributeError”,带有''Profile'对象没有属性'all''
  • @Kim:你不应该使用.all().profile 是一个单个 Profile 对象。
  • 是的,我没有。我使用了 self.fields['user_profile'].queryset = self.instance.user.profile 但奇怪的是我不断收到 AttributeError,''Profile' 对象没有属性'all''。
  • @Kim:那是因为您将它分配给表单字段的查询集,但指定表单字段没有任何意义:只有一个选项:的配置文件 i> 选定的用户。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-29
  • 2015-11-25
  • 2018-12-11
  • 2016-11-10
  • 1970-01-01
  • 2020-12-09
相关资源
最近更新 更多