找不到用户模型的反向查找

时间:2018-07-13 05:37:51

标签: django django-queryset

我正在使用Django 2.0,并且创建了自定义用户模型(如果有帮助的话)。

我希望能够检索给定用户帐户的一组角色实例。用户帐户可以作为给定公司实例的所有者或雇员被包括在内。但是,当我尝试执行user.employee_set(或user.owner_set)时,没有任何结果。

用户类别

class User(AbstractBaseUser):
    email = models.EmailField(max_length=254,unique=True,null=False,blank=False)

    staff = models.BooleanField(default=False)

    admin = models.BooleanField(default=False)

    USERNAME_FIELD  = 'email'
    REQUIRED_FIELDS = []

    def __str__(self):
        return self.get_full_name()

    def get_full_name(self):
        return self.first_name + " " + self.last_name

    def get_short_name(self):
        return

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_active(self):
        return self.active

    @property
    def is_staff(self):
        return self.staff

    @property
    def is_admin(self):
        return self.admin

员工阶层

class Employee(models.Model):
    class Meta:
        unique_together = (('user','company'),)

    user = models.ForeignKey(to=User,on_delete=models.CASCADE,related_name='employee_accounts')
    company = models.ForeignKey(to='Company',on_delete=models.CASCADE)

所有者类

class Owner(models.Model):
    class Meta:
        unique_together = (('user','company'),)

    user = models.ForeignKey(to=User,on_delete=models.CASCADE,related_name='owner_accounts')
    company = models.ForeignKey(to='Company',on_delete=models.CASCADE)

当我查找user.owner_accounts或user.employee_accounts时,我得到的结果是空的。我检查了用户帐户是否确实有员工记录和所有者记录,每个记录都引用了该记录。如果我执行Employee.objects.get(user = user)或Owner.objects.get(user = user),则它将成功并检索适当的用户包装对象。我对ForeignKey的工作方式有误解吗?我以为,除非我弄乱了模型定义中的某些内容,否则该设置将允许我进行反向查找。

1 个答案:

答案 0 :(得分:0)

这样检查就可以了

u1 = User.objects.get(pk=1)
u1.employee_accounts.all()