Django模型的额外参数

时间:2010-02-26 21:38:18

标签: python django wrapper django-forms

使用Django模型,我想实现这个目标:

class Foo(models.Model):
    name = models.CharField(max_length=50)

    #wrapping the save function, including extra tasks
    def save(self, *args, **kwargs):
        super(Foo, self).save(*args, **kwargs)

            if extra_param:
            ...do task 1
        else:
            ...do task 2

虽然装箱Foo我想传递

Foo(name="Bill Gates",extra_param=True).save() # now triggers the task 1
Foo(name="Bill Gates").save() # now triggers the task 2

如何做到这一点?我也对任何其他建议持开放态度:))

由于

1 个答案:

答案 0 :(得分:9)

您可以在模型中定义非持久字段。

class Foo(models.Model):
    name = models.CharField(max_length=50)
    extra_param = False

def save(self, *args, **kwargs):
    ... 
    print self.extra_param

或者,您可以这样做:

Foo(name="Bill Gates").save(extra_param=True)

def save(self, *args, **kwargs):
    ... 
    print kwargs["extra_param"]