如何在Django中为扩展模型设置默认值?

时间:2021-04-13 22:52:34

In a Mezzanine project, I have defined a simple Photo model that extends the core Page model:

在一个夹层项目中,我定义了一个简单的照片模型来扩展core Page模型:

from django.db import models
from mezzanine.pages.models import Page

class Photo(Page):
    image = models.ImageField(upload_to="photos")
    #publish_date = models.DateTimeField(auto_now_add=True, blank=True) #problematic

When I tried to re-define the publish_date field, I got error:

当我试图重新定义publish_date字段时,我得到了错误:

django.core.exceptions.FieldError: Local field 'publish_date' in class 'Photo' *es with field of similar name from base class 'Page'

I want to avoid filling publish_date in admin page each time I create a photo. So wondering how should I set it it to now() without touching the original Page model?

我希望避免在每次创建照片时在管理页面中填写publish_date。所以我想知道如何在不接触原始页面模型的情况下将它设置为now() ?

1 个解决方案

#1


1  

You can't change the definition of a field in a derived class of a model -- what if the base class relies on the existing behavior in any way?

您不能更改模型派生类中的字段定义——如果基类以任何方式依赖于现有行为,该怎么办?

What I'd suggest is define a custom save() method in your Photo class that adds the date, then calls the super() save:

我建议在Photo类中定义一个自定义save()方法,添加日期,然后调用super() save:

import datetime
def save(self, *args, **kwargs):
    if not self.pk:
        # instance is being created.
        self.publish_date = datetime.datetime.now()
    super(Photo, self).save(*args, **kwargs)

If you find yourself doing this a lot, you could create a mixin that adds this functionality to any class.

如果您发现自己经常这样做,您可以创建一个mixin,将该功能添加到任何类中。

#1


1  

You can't change the definition of a field in a derived class of a model -- what if the base class relies on the existing behavior in any way?

您不能更改模型派生类中的字段定义——如果基类以任何方式依赖于现有行为,该怎么办?

What I'd suggest is define a custom save() method in your Photo class that adds the date, then calls the super() save:

我建议在Photo类中定义一个自定义save()方法,添加日期,然后调用super() save:

import datetime
def save(self, *args, **kwargs):
    if not self.pk:
        # instance is being created.
        self.publish_date = datetime.datetime.now()
    super(Photo, self).save(*args, **kwargs)

If you find yourself doing this a lot, you could create a mixin that adds this functionality to any class.

如果您发现自己经常这样做,您可以创建一个mixin,将该功能添加到任何类中。