Django通用外键和select_related

Cla*_*ash 6 django django-models

我正在尝试使用与通用外键的关系选择模型,但它没有按预期工作.

我认为使用代码可以更好地说明和理解

class ModelA(models.Model):
 created = models.DateTimeField(auto_now_add=True)

class ModelB(models.Model):
 instanceA = models.ForeignKey(ModelA)

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

class ModelC(models.Model):
 number = models.PositiveIntegerField()
 bInstances = generic.GenericRelation(ModelB)

# Creating an instance of A and C
aInstance=ModelA.objects.create()
cInstance=ModelC.objects.create(number=3)

# Adding instance of C to the B_set of instance A
aInstance.modelb_set.add(content_object=cInstance)

# Select all ModelA instances that have C as content object? Does not work
whatIWant = ModelA.objects.filter(modelb__content_object=modelCInstance)

# Pseudo-solution, requires calling whatIWant.modelA
whatIWant = cInstance.bInstances.select_related("modelA") 
Run Code Online (Sandbox Code Playgroud)

为了清楚起见,我希望这条线有效:ModelA.objects.filter(modelb__content_object=modelCInstance)显然django不支持在过滤器关系上使用content_object.

提前致谢!

Ber*_*ant 9

看看http://www.djangoproject.com/documentation/models/generic_relations/.并尝试:

ctype = ContentType.objects.get_for_model(modelCInstance)
what_you_want = ModelA.objects.filter(modelb__content_type__pk=ctype.id, 
                                      modelb__object_id=modelCInstance.pk)
Run Code Online (Sandbox Code Playgroud)

请查看一些django 编码/命名约定,以使您的代码更易于阅读和理解!

  • 由于ContentTypes等不是django核心的一部分,内置的`filter`不知道如何处理这样的查询,所以你必须自己过滤content_type和object_id! (2认同)