3

假设我有以下代码:

 class MyModel(models.Model):
     ...
     ...

    def save(self, *args, **kwargs):
        # pre-save edits can go here...
        super(MyModel, self).save(*args, **kwargs)

当我创建并保存模型 MyModel(blah, blah, blah) 时,输入字段之一可能是“无”。在覆盖的保存方法中,目标是检查字段是否为空,如果是,则将其更改为其他默认值。

输入字段是 args 还是 kwargs?并且覆盖 save() 甚至是正确的方法吗?

我在想这样的事情:

    def save(self, *args, **kwargs):
        if 'username' in args and args['username'] is None:
              args['username'] = some_default_value
        super(MyModel, self).save(*args, **kwargs)

那么输入参数在哪里呢?args* 或 **kwargs,谢谢。

4

1 回答 1

5

我认为最好是一个pre_save信号来查看输入值是否为None

from django.db import models
from django.db.models.signals import pre_save
from django.dispatch import receiver

class MyModel(models.Model):
    field1 = models.TextField()
    field2 = models.IntegerField()

@receiver(pre_save, sender=MyModel)
def mymodel_save_handler(sender, instance, *args, **kwargs):
     if instance.field1 is None or instance.field1 == "":
         instance.field1 = default_value

如果您更喜欢覆盖save方法,您可以访问model fieldswithself

 def save(self, *args, **kwargs):
        if self.username is None:
              self.username = some_default_value
        super(MyModel, self).save(*args, **kwargs)
于 2013-07-20T23:39:14.433 回答