2010-09-24 43 views
6

我正在嘗試使用與通用外鍵的關係來選擇模型,但它不像預期的那樣工作。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不支持。

在此先感謝!

+0

你期望什麼?如果沒有問題,我們不能回答問題。 – 2010-09-24 19:11:42

+0

爲了讓它更清晰,我編輯了帖子,對不起 – Clash 2010-09-24 19:23:07

回答

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,使你的代碼更容易閱讀和理解!

+0

感謝您的提示!這是唯一的方法嗎?我正在尋找更友好的東西,謝謝! – Clash 2010-09-24 19:44:56

+2

因爲ContentTypes等不是django核心的一部分,所以內建的'filter'不知道如何處理這些查詢,所以你必須過濾你自己的content_type和object_id! – 2010-09-24 19:52:47