2016-03-28 48 views
0

的情況下我有一個下面的抽象類通用外鍵必須是內容類型

class Manufacturer(models.Model): 
    company=models.CharField(max_length=255) 

    class Meta: 
     abstract = True 

現在2班從上面繼承: -

class Car(Manufacturer): 
    name = models.CharField(max_length=128) 

class Bike(Manufacturer): 
    name = models.CharField(max_length=128) 

現在我想將它們連接與功能,所以我創建以下類: -

class Feature(models.Model): 
    name= models.CharField(max_length=255) 
    limit=models.Q(model = 'car') | models.Q(model = 'bike') 
    features = models.ManyToManyField(ContentType, through='Mapping',limit_choices_to=limit) 

class Mapping(models.Model): 
    category=models.ForeignKey(Category, null=True, blank=True) 
    limit=models.Q(model = 'car') | models.Q(model = 'bike') 
    content = models.ForeignKey(ContentType, on_delete=models.CASCADE,limit_choices_to=limit,default='') 
    object_id = models.PositiveIntegerField(default=1) 
    contentObject = GenericForeignKey('content', 'object_id') 

    class Meta: 
     unique_together = (('category', 'content','object_id'),) 
     db_table = 'wl_categorycars' 

但是,當我嘗試在shell命令中創建實例我得到一個呃ror,同時創建映射實例

「Mapping.content」必須是「ContentType」實例。

car1=Car(company="ducati",name="newcar") 
bike1=Bike(company="bike",name="newbike") 

cat1=Category(name="speed") 

mapping(category=cat1, content=car1) # ---> i get error at this point 

如何入手呢?

+0

清楚地閱讀文檔。 https://docs.djangoproject.com/en/1.9/ref/contrib/contenttypes/ – Tushant

+0

試着理解這段代碼,你就會知道它。從django.contrib.contenttypes.fields導入從django.contrib.contenttypes.models GenericForeignKey 導入的ContentType 類TaggedItem(models.Model): 標籤= models.SlugField() CONTENT_TYPE = models.ForeignKey(ContentType的,on_delete = models.CASCADE) OBJECT_ID = models.PositiveIntegerField() content_object = GenericForeignKey( 'CONTENT_TYPE', 'OBJECT_ID') 高清__str __(個體經營):#Python的2 __unicode__ 回報self.tag – Tushant

+0

我沒去,可通過文檔,但是當使用unique_together時,我不能將contentObject放入模型中,它會拋出錯誤,指出多個表繼承 –

回答

1

您需要與創建對象:

Mapping(
    category=cat1, 
    content=ContentType.objects.get_for_model(car1), 
    object_id=car.id 
) 

順便說一句,我會評爲該領域的content_type代替content避免ambuiguity。請參閱official documentation for more information

0

您應該使用contentObject參數來將模型對象填充爲GenericForeignKey而不是content

像這樣的東西應該工作:

Mapping(category=cat1, contentObject=car1)

相關問題