我正在嘗試使用與通用外鍵的關係來選擇模型,但它不像預期的那樣工作。Django的通用外鍵和select_related
我認爲這是更好地說明和理解的代碼
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不支持。
在此先感謝!
你期望什麼?如果沒有問題,我們不能回答問題。 – 2010-09-24 19:11:42
爲了讓它更清晰,我編輯了帖子,對不起 – Clash 2010-09-24 19:23:07