gpt4 book ai didi

python - Django 多重继承与不同的表

转载 作者:行者123 更新时间:2023-12-05 04:10:47 25 4
gpt4 key购买 nike

我尝试创建一些模型。我实际上看了一些例子,但大多数都不起作用。示例:

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

所以我的目标是通过这样的东西获得值(value) -> 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)
但这不会在日期和书籍/文章之间生成链接。我只能给那天加个名字。

最佳答案

问题是因为两个模型的主字段都是 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)

关于python - Django 多重继承与不同的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43988580/

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