Django:如何使用设置执行查询。AUTH_USER_MODEL?

时间:2019-03-20 11:01:22

标签: django django-models

这是我的模特

class Company(models.Model):
    user    = models.ForeignKey(settings.AUTH_USER_MODEL,related_name="Company_Owner",on_delete=models.CASCADE,null=True,blank=True)
    name    = models.CharField(max_length=50,blank=False)
    auditor = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='main_auditor',blank=True)

我想执行一个查询,该查询将显示与特定审核员相关的公司的列表...

如何在Django中使用settings.AUTH_USER_MODEL查询?

有人知道吗?

请帮助

2 个答案:

答案 0 :(得分:3)

您可以使用get_user_model()这样操作:

from django.contrib.auth import get_user_model

User = get_user_model()

first_user = User.objects.first()

first_user.Company_Owner.all()  # will get all companies associated with the User

答案 1 :(得分:1)

您的模型关系命名不正确,请更改related_name参数,因为它们需要表示您正在获取Company对象:

class Company(models.Model):
    user    = models.ForeignKey(settings.AUTH_USER_MODEL,related_name="owned_companies",on_delete=models.CASCADE,null=True,blank=True)
    name    = models.CharField(max_length=50,blank=False)
    auditor = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='audited_companies',blank=True)

一旦您有user(例如user = self.request.user)就可以执行以下操作:

user.owned_companies.all()  # companies for which the user is the owner
user.audited_companies.all()  # companies for which the user is a main auditor
user.owned_companies.filter(auditor=user)  # companies of which the user is both owner and auditor