我试图创建一些模型。我实际上看了一些例子,但大多数都没有工作。例如:
class Piece(models.Model):
name = models.CharField(max_length=100)
class Meta:
abstract = True
class Article(Piece):
pass
class Book(Piece):
pass
class Monday(Book, Article):
pass
class Tuesday(Book, Article):
pass
所以我的目标是通过这样的方式获得价值 - > Monday.Article.name
。
我希望每个工作日都有不同的表格,其中包含文章的名称。这是我得到的错误:
ERRORS:
Testing.Monday: (models.E005) The field 'id' from parent model 'Testing.book' clashes with the field 'id' from parent model 'Testing.article'.
Testing.Monday: (models.E005) The field 'name' from parent model 'Testing.book' clashes with the field 'name' from parent model 'Testing.article'.
Testing.Tuesday: (models.E005) The field 'id' from parent model 'Testing.book' clashes with the field 'id' from parent model 'Testing.article'.
Testing.Tuesday: (models.E005) The field 'name' from parent model 'Testing.book' clashes with the field 'name' from parent model 'Testing.article'.
看起来我的文章和图书使用了相同的名称。这是如何工作的?
编辑:使用此:
class Article(Piece):
article_id = models.AutoField(primary_key=True)
class Book(Piece):
book_id = models.AutoField(primary_key=True)
会导致此错误:
Testing.Monday: (models.E005) The field 'piece_ptr' from parent model
'Testing.book' clashes with the field 'piece_ptr' from parent model
'Testing.article'.
唯一的解决方案是:
article_to_piece = models.OneToOneField(Piece, parent_link=True)
但这不会在日期与书籍/文章之间产生链接。我只能在当天添加一个名字。
答案 0 :(得分:0)
问题是因为两个模型的主要字段都是id,而且一个表不能有2个基于相同名称的列,这样做会解决你的错误
class Article(Piece):
id = models.AutoField(primary_key=True)
name= models.CharField(max_length=100)
class Book(Piece):
book_id = models.AutoField(primary_key=True)
book_name= models.CharField(max_length=100)
答案 1 :(得分:0)
您应该尝试在子类上调用 init ,例如:
class Monday(Book, Article):
id = models.AutoField(primary_key=True)
name= models.CharField(max_length=100)
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
class OtherDay(Book, Article):
book_id = models.AutoField(primary_key=True)
book_name= models.CharField(max_length=100)
def __init__(self, *args, **kwargs):
return super().__init__(*args, **kwargs)
这是因为,作为Python类,super()方法将仅调用一次超类定义,而简单继承将为每个超类调用 ini ()。