Django查询涉及泛型关系的模型

Django querying on model which is involved in generic relation

这里我有 2 个模型,CompanyUserSupervisionCompany 作为外键与通用关系模型 UserSupervision.

关联

我想查询如下:

Company.objects.filter(**{'usersupervision__content_type': Company,
                          'usersupervision__user': some_user,
                          'usersupervision__date_cancelled': None})

所以,我想得到 some_user 的所有公司出现在 UserSupervision 模型中。我知道 CompanyUserSupervision 没有直接关系,所以我想,也许我必须将原始 sql 与连接一起使用?或者其他更合适的解决方案?

class Company(models.Model):
    id = models.UUIDField(blank=True, editable=False, primary_key=True, default=uuid.uuid4)
    name = models.CharField(max_length=150, unique=True)

    users = models.ManyToManyField(User, related_name='companies', through='CompanyMembership')
    date_created = models.DateTimeField('created date', blank=True, editable=False, auto_now_add=True)
    date_updated = models.DateTimeField('updated date', blank=True, editable=False, auto_now=True)


class UserSupervision(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    supervision = models.ForeignKey(Supervision, on_delete=models.SET_NULL, null=True)

    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.UUIDField()
    content_object = GenericForeignKey()

    date_assigned = models.DateTimeField('assigned date', blank=True, editable=False, auto_now_add=True)
    date_cancelled = models.DateTimeField('cancelled date', blank=True, null=True, default=None)

所以您想在 UserSupervision 中找到某个证书 UserSupervision.user 的所有公司?类似于:

user_supervisions = UserSupervision.objects.filter(
    content_type=ContentType.objects.get_for_model(Company),
    user=some_user,
    date_cancelled=None
).order_by('content_type_id', 'object_id').distinct('content_type_id', 'object_id')

companies = [us.object_id for us in usersupervisions]  # Loop to create list of company ids.

如果您不使用 PostgreSQL,您可以 drop the order_by and distinct,但需要更改公司循环以解决重复条目。