如何在GenericRelation中按外键过滤?

时间:2015-09-01 20:24:45

标签: python django django-models

以下是我的模特:

class Model1(models.Model):
    ...
    distributor_links = GenericRelation(Relation, related_query_name="distributor_persons")

class Model2(models.Model):
    ...
    distributor_links = GenericRelation(Relation, related_query_name="distributor_groups")

class Model3(models.Model):
    pass

class Relation(models.Model):
    link = models.ForeignKey(Model3)

    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

现在我想获得与Model3对象关联的所有Model1Model2对象。我的查询如下:

Model1.objects.filter(distributor_links=self.object)

其中self.objectModel3个实例。 该查询引发错误:Cannot query "query": Must be "Relation" instance 我明白为什么它会抛出这个错误。这里distributor_links=self.object无法将Relation对象与Model3对象进行比较,但我仍然不知道如何编写我想要的查询。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

Is it possible to resolve ContentType of object and use it and object id for filtering.

content_type = ContentType.objects.get_for_model(self.object)

Model1.objects.filter(distributor_links__content_type=content_type, distributor_links__object_id=self.object.id)

答案 1 :(得分:1)

If self.object is a Model3 instance, you could:

Model1.objects.filter(distributor_links__link=self.object)

This quiestion is similar to: Django - How to use a filter with a foreign key field?

That is, the name of the field, followed by a double underscore (__), followed by the name of the field in the new model, and so on for as many models as you want to join.

For more information: https://docs.djangoproject.com/en/dev/ref/models/querysets/