2012-03-01 91 views
2

我一直在試圖爲我的應用程序實現一個標記系統,其中每個內容類型只允許某些標記。Django間接通用關係

我試着在Tag模型上設置內容類型,並在TagAttribution模型上使用這個值,並得到了...有趣的結果。

代碼:

from django.db import models 
from django.contrib.contenttypes.models import ContentType 
from django.contrib.contenttypes import generic 
from django.contrib.auth.models import User 

class Tag(models.Model): 
    value = models.CharField(max_length=32) 
    created_by = models.ForeignKey(User) 
    appliable_to = models.ForeignKey(ContentType) 

    def __unicode__(self): 
     return self.value 

class TagAttribution(models.Model): 
    tag = models.ForeignKey(Tag) 
    object_id = models.PositiveIntegerField() 
    content_object = generic.GenericForeignKey('tag__appliable_to', 'object_id') 

    def __unicode__(self): 
     return "%s for id %s of class %s" % (self.tag.value, self.object_id, self.content_object.model) 

殼體試驗:

ct = ContentType.objects.get(model='company') 
tag = Tag() 
tag.value = 'value' 
tag.created_by = User.objects.get(id=1) 
tag.appliable_to = ct 
tag.save() 
ta = TagAttribution() 
ta.tag = tag 
ta.object_id = Company.objects.get(id=1).id 
ta.content_object = ta.tag.appliable_to 
ta.save() 
ta 

輸出:

<TagAttribution: value for id 13 of class company> 

我不明白這種行爲;如果我使用公司ID 1,爲什麼它有ID 13?

回答

3

錯誤是在這裏:

ta.content_object = ta.tag.appliable_to 

這裏的ta.content_object不是公司的對象,但ContentType的。正確的代碼應該是:

ta.content_object = Company.objects.get(id=1).id 

而且,你不必直接設置ta.object_id,它是由GenericForeignKey領域所做

+0

可悲的是,這似乎並沒有工作。你的代碼呈現'AttributeError:'int'對象沒有屬性'_state'。我刪除了最後一個'id',錯誤是'AttributeError:'Company'對象沒有屬性'model'' – Wilerson 2012-03-02 13:41:11

+0

最終,我發現除了'id'之外,你的解決方案是正確的,我的代碼是打破'TagAttribution'中的'__unicode__'方法。 – Wilerson 2012-03-02 19:20:15