Django - Overriding the Model.create() method?

后端 未结 7 976
忘了有多久
忘了有多久 2020-12-04 08:36

The Django docs only list examples for overriding save() and delete(). However, I\'d like to define some extra processing for my models onl

7条回答
  •  天涯浪人
    2020-12-04 09:41

    Overriding __init__() would cause code to be executed whenever the python representation of object is instantiated. I don't know rails, but a :before_created filter sounds to me like it's code to be executed when the object is created in the database. If you want to execute code when a new object is created in the database, you should override save(), checking if the object has a pk attribute or not. The code would look something like this:

    def save(self, *args, **kwargs):
        if not self.pk:
            # This code only happens if the objects is
            # not in the database yet. Otherwise it would
            # have pk
        super(MyModel, self).save(*args, **kwargs)
    

提交回复
热议问题