Django if field = blank,set field = 1?

时间:2011-02-16 03:03:43

标签: django django-models

我可以在models.py或admin.py文件中使用条件语句来执行以下操作吗?:

if field (trying to be saved) == blank, set field = 1.

感谢您的帮助。请让我澄清是否需要。

1 个答案:

答案 0 :(得分:1)

您可能希望覆盖模型上的保存方法。

def save(self, *args, **kwargs):
    # this is your model "trying" to be saved, before the "real"
    # save is called by super below

    if self.field == 'blank':
        self.field = 1
    super(MyModel, self).save(*args, **kwargs)

http://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods

如果您想在admin.py中执行此操作(因此管理员特定的行为,而非全局模型行为),您可能希望覆盖save_model上的ModelAdmin

# code mostly from docs
class ArticleAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        if obj.field == 'blank':
           obj.field = 1
        obj.save()

http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model