如何创建具有M2M和FK关系的Django模型的精确副本

2024-03-29 15:51:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Django模型,它已经存在,我想复制它,但是由于ForeignKeyManyToMany之间的相关名称冲突,我想不出一个简单的方法

例如,让我们调用我当前拥有的模型Dog

class Dog(models.Model):
    name = models.CharField()
    owner = models.ForeignKey('myapp.Owner')
    breeds = models.ManyToMany('myapp.Breed', help_text="Remember, animals can be mixed of multiple breeds.")

我想用一个不同的数据库表和名称复制这个模型,以便在其他地方使用。我尝试使用abstract base class

class AnimalAbstract(models.Model):
    name = models.CharField()
    owner = models.ForeignKey('myapp.Owner')
    breeds = models.ManyToMany('myapp.Breed', help_text="Remember, animals can be mixed of multiple breeds.")

    class Meta:
        abstract = True

class Dog(AnimalAbstract):
    pass

class Cat(AnimalAbstract):
    pass

这失败是因为related_name冲突。你知道吗

有没有什么方法可以自动复制这样的模型而不必显式地重新定义每个ForeignKeyManyToMany?你知道吗

抢先回答问题:是的,我知道multi-table inheritance,我不想用它。我还知道,我可以简单地将所有这些存储在同一个表中,并使用proxy models和自定义管理器自动筛选出错误类型的动物,但我也不希望这样——我希望它们位于不同的数据库表中。


Tags: 方法name模型名称modelmodelsmyappclass
1条回答
网友
1楼 · 发布于 2024-03-29 15:51:38

https://docs.djangoproject.com/en/1.8/topics/db/models/#abstract-related-name

为了解决这个问题,当您在抽象基类(仅)中使用相关的名称时,名称的一部分应该包含%(app_label)s%(class)s。你知道吗

  • %(class)s替换为使用该字段的子类的小写名称。你知道吗
  • %(app_label)s被包含子类的应用程序的小写名称替换。每个安装的应用程序名称必须是唯一的,每个应用程序中的模型类名也必须是唯一的,因此最终得到的名称将是不同的。你知道吗

例如:

 class Dog(models.Model):
     name = models.CharField()
     owner = models.ForeignKey(
         'myapp.Owner', 
         related_name="%(app_label)s_%(class)s_dogs")

     breeds = models.ManyToMany(
         'myapp.Breed', 
         help_text="Remember, animals can be mixed of multiple breeds.", 
         related_name="%(app_label)s_%(class)s_dogs")

相关问题 更多 >