gpt4 book ai didi

django - Django 中显示错误的通用外键必须是内容类型的实例

转载 作者:行者123 更新时间:2023-12-02 04:11:53 25 4
gpt4 key购买 nike

我有一个抽象类

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 命令中创建实例时,我在创建映射实例时遇到错误

"Mapping.content" must be a "ContentType" instance.

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

我该如何处理?

最佳答案

你需要创建你的对象:

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

顺便说一下,我会将该字段命名为 content_type 而不是 content 以避免歧义。查看official documentation for more information .

关于django - Django 中显示错误的通用外键必须是内容类型的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36258032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com