Django通用外键和select_related

时间:2010-09-24 19:07:48

标签: 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") 

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

提前致谢!

1 个答案:

答案 0 :(得分: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)

请查看一些django coding/naming conventions,以便让您的代码更易于阅读和理解!