DJANGO 模型代理继承

DJANGO models proxy inharitence

我想为我的 2 个 Django 模型类添加 'tools' class 的方法。 每个 class 都将使用与它自己的模型示例相同的方法:

class mapA(models.Model):
     mInd = models.IntegerField()
     scId = models.IntegerField()

class mapB(models.Model):
     mInd = models.IntegerField()
     scId2 = models.IntegerField()

我想将 checkInput() 之类的方法添加到它们中。 所以我可以 运行:

mapBInstance.checkInput();
mapAInstance.checkInput();

每次 checkInput 运行 秒检查 mapA 或 mapB 中的数据。

我考虑创建一个工具 class 并让每个模型都继承它。 这样工具 class 将具有与两个地图相同的逻辑。

当我阅读 django docs 时,我没有看到这种情况的示例,只有关闭解决方案。 这是正确的解决方案吗(使用代理 class)?

class Tools():
   def __init__():
      ...init class...
   def checkInput():
       ..make the checks..

class MapA(Tools, models.Model):
     mInd = models.IntegerField()
     scId = models.IntegerField()

     def checkSelf():
         self.checkInput(self.objects.filter(....))

class MapB(Tools, models.Model):
     mIndB = models.IntegerField()
     scIdB = models.IntegerField()
     def checkSelf():
         self.checkInput(self.objects.filter(....))

如果您希望 MapAMapB(如果您遵循 PEP-8 将非常有帮助)是不同的模型,代理模型将无济于事。代理模型是在Python中不同的模型,但在数据库中它与它继承的模型完全相同。创建不直接继承自单个具体模型(在数据库中具有 table 的模型)的代理模型是错误的。

你要找的是一个抽象基础 class:

class Tools(models.Model):
    ...

    class Meta:
        abstract = True

class MapA(Tools):
    ...

class MapB(Tools):
    ...

抽象模型不会在数据库中创建自己的table。相反,就好像 Tools 中定义的所有内容都已在 MapAMapB 中定义,但 Tools class 被忽略。这允许您只指定一次所有方法和字段,但在数据库中仍然有两个单独的 table。

一些事情...


Python里没有this,叫self


如果您在 Python 2.x,tools 应该继承自 object。在 Python 3 中,它是隐含的,但不会造成伤害:

class tools(object):
    ...

如果你在你的 mixin class (tools) 中覆盖 __init__,那么 map classes 可能应该从它继承 第一个:

class mapA(tools, models.Model):
    ...

仅在确实需要时覆盖 __init__,它会变得复杂。


Class 名称几乎总是采用 CamelCase。这不是必需的,而是约定俗成的。另外,透明地命名 mixin classes 是个好主意:

class ToolsMixin(object):
    ...

class MapA(ToolsMixin, models.Model):
    ...

除此之外,您完全可以在 mixin 中添加一个方法并在您的模型中使用它。不需要 Django 代理模型。