Har*_*uja 2 django django-generic-relations
我有一个以下抽象类
class Manufacturer(models.Model):
company=models.CharField(max_length=255)
class Meta:
abstract = True
Run Code Online (Sandbox Code Playgroud)
现在有 2 个类继承自上面:-
class Car(Manufacturer):
name = models.CharField(max_length=128)
class Bike(Manufacturer):
name = models.CharField(max_length=128)
Run Code Online (Sandbox Code Playgroud)
现在我想将它们与功能链接起来,所以我创建了以下类:-
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'
Run Code Online (Sandbox Code Playgroud)
但是当我尝试在 shell 命令中创建实例时,在创建映射实例时出现错误
“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
Run Code Online (Sandbox Code Playgroud)
我该如何继续?
您需要使用以下方法创建对象:
Mapping(
category=cat1,
content=ContentType.objects.get_for_model(car1),
object_id=car.id
)
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我会命名该字段,content_type而不是content为了避免歧义。请参阅官方文档以获取更多信息。
| 归档时间: |
|
| 查看次数: |
4756 次 |
| 最近记录: |