【问题标题】:Django 1.7 migrations with abstract base classes带有抽象基类的 Django 1.7 迁移
【发布时间】:2014-09-24 15:07:11
【问题描述】:

我正在尝试升级到 Django 1.7 并从 South 切换到 Django 的集成迁移。我的模型遇到了问题。我有一个基类:

class CalendarDisplay():
    """
    Inherit from this class to express that a class type is able to be displayed in the calendar.
    Calling get_visual_end() will artificially lengthen the end time so the event is large enough to
    be visible and clickable.
    """

    start = None
    end = None

    def __init__(self):
        pass

    def get_visual_end(self):
        if self.end is None:
            return max(self.start + timedelta(minutes=15), timezone.now())
        else:
            return max(self.start + timedelta(minutes=15), self.end)

    class Meta:
        abstract = True

下面是一个继承它的类的例子:

class Reservation(models.Model, CalendarDisplay):
    user = models.ForeignKey(User)
    start = models.DateTimeField('start')
    end = models.DateTimeField('end')
    ...

现在我尝试迁移我的应用,但收到以下错误:python manage.py makemigrations

Migrations for 'Example':
  0001_initial.py:
    - Create model Account
    ...
    ValueError: Cannot serialize: <class Example.models.CalendarDisplay at 0x2f01ce8>
    There are some values Django cannot serialize into migration files.

我有哪些解决方法? Django 1.7 迁移可以处理抽象基类吗?我宁愿保留我的抽象基类并继承它,但是,将必要的函数复制并粘贴到适当的类中是最后的手段。

【问题讨论】:

    标签: django


    【解决方案1】:

    你的抽象基类应该扩展models.Model:

    class CalendarDisplay(models.Model):
        ...
    

    您的子类应该只扩展CalendarDisplay- 它不需要扩展models.Model

    class Reservation(CalendarDisplay):
        ...
    

    此外,您需要在 CalendarDisplay 中不覆盖 __init__,或者您需要在 init 中调用 super

    def __init__(self, *args, **kwargs):
        super(CalendarDisplay, self).__init__(*args, **kwargs)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-13
      • 1970-01-01
      • 2014-05-28
      • 2014-11-19
      • 2015-10-31
      • 2015-02-09
      • 2015-09-21
      • 2014-12-21
      相关资源
      最近更新 更多