查询扩展用户模型返回错误

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了查询扩展用户模型返回错误相关的知识,希望对你有一定的参考价值。

我在进行以下查询时收到错误:

Election.objects.all().exclude(candidate__UserID=request.user).filter(Gender=request.user.Profile.Gender).filter(CandidateReg=True)

对于这个模型:

class Election(models.Model):
    Name = models.CharField(max_length=20)
    CandidateReg = models.BooleanField(default=True)
    VotingOpen = models.BooleanField(default=False)
    Description = models.CharField(max_length=255, null=True, blank=True)
    GENDERS = (("M","Male"), ("F","Female"))
    Gender = models.CharField(max_length=1, choices=GENDERS, default="M")
    Seats = models.IntegerField(default=7)
    FlipGrid = models.URLField(null=True, blank=True)
    Complete = models.BooleanField(default=False)

此错误中描述了此问题:

Traceback (most recent call last):
      File "/home/elections/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
        response = get_response(request)
      File "/home/elections/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "/home/elections/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "/home/elections/elections-real/elections/views.py", line 139, in add_candidate
        elections = Election.objects.all().exclude(candidate__UserID=request.user).filter(Gender=request.user.Profile.Gender).filter(CandidateReg=True)
      File "/home/elections/venv/lib/python3.6/site-packages/django/utils/functional.py", line 239, in inner
        return func(self._wrapped, *args)
    AttributeError: 'User' object has no attribute 'Profile'

它似乎表明问题是在当前用户的配置文件中引用Genderdata - 用户模型的扩展。这显示在这里:

class Profile(models.Model):
    UserID = models.OneToOneField(User, on_delete=models.CASCADE)
    GENDERS = (("M","Male"), ("F","Female"))
    Gender = models.CharField(max_length=1, choices=GENDERS)
    UserTypeID = models.ForeignKey(UserType, on_delete=models.PROTECT, blank=True, null=True)
    EmailConfirmed = models.BooleanField(default=False)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(UserID=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

如果不按上述方式,如何正确引用登录用户配置文件的Gender属性?

答案

一对一字段的反向访问器始终是模型的低级名称:因此它将是request.user.profile...

如果您遵循标准的PEP-8兼容样式并用小写字母命名所有字段 - gendervoting_openemail_confirmed等,那么这对您来说就不那么令人惊讶了。另请注意,给出以ID结尾的关系字段名称不是最佳做法访问整个相关对象,而不仅仅是ID,所以你的UserID应该被称为user

最后,关于性别,请阅读Falsehoods Programmers believe about Gender并考虑您是否真的需要询问此信息。

以上是关于查询扩展用户模型返回错误的主要内容,如果未能解决你的问题,请参考以下文章

安卓。片段 getActivity() 有时返回 null

保存扩展用户模型的问题

中继片段传播不起作用

VSCode创建自定义用户片段

为啥此代码片段返回意外结果?

如何从片段返回主要活动