Python 无法定义';通过';Django中共享一个基类的两个模型的关系

Python 无法定义';通过';Django中共享一个基类的两个模型的关系,python,django,postgresql,Python,Django,Postgresql,我有一个“set”模型,它与“Item”模型有多对多的关系。问题在于“set”是Item的一个子类(所有内容都是项目中的一项) 它工作得很好,直到我尝试创建一个名为“order”的中介模型的“through”关系,我正在定义该模型,以便可以在“Set”中对“Items”进行排序 当我试图定义关系时,出现以下错误: ERRORS: curate.Set.items_: (fields.E001) Field names must not end with an underscore. curate

我有一个“set”模型,它与“Item”模型有多对多的关系。问题在于“set”是Item的一个子类(所有内容都是项目中的一项)

它工作得很好,直到我尝试创建一个名为“order”的中介模型的“through”关系,我正在定义该模型,以便可以在“Set”中对“Items”进行排序

当我试图定义关系时,出现以下错误:

ERRORS:
curate.Set.items_: (fields.E001) Field names must not end with an underscore.
curate.order.set: (fields.E304) Reverse accessor for 'order.set' clashes with reverse accessor for 'order.item'.
        HINT: Add or change a related_name argument to the definition for 'order.set' or 'order.item'.
我尝试将相关的_名称添加到Order.set和Order.item,但似乎不起作用。我可以让迁移变得愉快,但当我尝试迁移时,会出现一个错误,错误是:

ValueError: Cannot alter field curate.Set.items into curate.Set.items - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields)
型号.py


class Item(models.Model, AdminVideoMixin):

    title = models.TextField(max_length=5000)
    slug = models.SlugField(max_length=5000, default='')
   ...

class Video(Item):
    video_embed = EmbedVideoField(max_length=500)
    ...

class Article(Item):
    authors = models.CharField(max_length=10000)
    ...

class Podcast(Item):
    categories = models.CharField(max_length=5000, null=True, blank=True,)
    ...

class Episode(Item):
    author = models.CharField(max_length=10000, null=True,blank=True,)
    ...

class Set(Item):
    items = models.ManyToManyField(Item, related_name='setItems', max_length=5000, through='Order')
    front_page = models.BooleanField(max_length=300, blank=False, default=False, null=False)

class order(models.Model):
    item = models.ForeignKey(Item, on_delete=models.CASCADE,)
    set = models.ForeignKey(Set, on_delete=models.CASCADE,)
    order = models.CharField(max_length=64, default=0)

一旦创建了
ManyToMany
字段,您就不能将其更改为使用
关系。这是因为直通表现在将包含标准的
manytomy
关系无法填充的额外字段(这与使用直通表时不能使用
add
clear
remove
delete
的原因相同)。在删除
Set.items
之前,您需要在
Set
上创建一个新的
manytomy
字段,该字段使用直通关系,然后使用
Set.items
中的数据填充该字段

如果需要名为
items
的新字段,可以执行以下操作:

  • items
    更改为
    items\u old
    集合
    模型中,如果希望相关名称相同,则还需要更改相关名称(进行并运行迁移)
  • 使用直通关系添加新的
    字段(进行并运行迁移)
  • 项目中的数据填充新
    项目
    字段
  • Set

注意-就像卡图齐在他的评论中提到的,您可能不应该将字段命名为set

不要将python关键字用作类或变量名。设置这会是个大问题吗?我将更新它。不仅是
Set
model,而且是
order
model的
Set
字段。用大写字母命名你的班级是一个惯例。
set_items = Set.objects.filter(items__isnull=False)
Order.objects.bulk_create([
    Order(item=item, set=s)
    for s in set_items
    for item in s.items.all()
])