DRF继承CommonModel通用模型设置外键出现字段冲突报错如何解决
问题原因
你定义的CommonModel没有配置为Django抽象基类,默认触发了Django的多表继承规则:框架会为CommonModel单独创建数据库表,同时自动为每一个继承它的子类生成一个一对一关联字段,字段名默认为子类名的小写形式。
因为Tag、Vendor都是CommonModel的子类,所以CommonModel会自动生成tag、vendor两个隐式关联字段;而Product也继承了CommonModel,相当于Product从父类继承了这两个字段,你又在Product中自定义了同名的外键字段,就触发了字段冲突报错。
解决方案
将CommonModel设置为抽象基类即可,Django不会为抽象基类单独建表,只会将基类定义的公共字段复制到所有子类的表结构中,也不会自动生成子类的关联字段,不会再出现命名冲突。
修改后的CommonModel代码如下:
class CommonModel(models.Model): """Common fields that are shared among all models.""" created_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT, editable=False, related_name="+") updated_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.PROTECT, editable=False, related_name="+") created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True, editable=False) class Meta: abstract = True
内容的提问来源于stack exchange,提问作者Empusas
相关产品推荐
相关产品推荐

