开发者

Extra parameter for Django models

With Django models, I want to achieve this:

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:
  开发者_StackOverflow          ...do task 2

And while crating Foo I want to pass such as

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

How can this be done? I am also open to any other suggestions :)

Thanks


You can define non-persistent fields in your model.

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

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

Alternatively, you can do:

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜