7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

django-modelsのsaveメソッドを上書きする

Posted at

データベースにinsertする直前になにか処理をしてほしい場合にはModelのsaveメソッドを上書きする

class Event(models.Model):

    class Meta:
        unique_together = ('name', 'held_date')

    id = models.CharField(primary_key=True, max_length=20)
    name = models.CharField(max_length=8)
    held_date = models.DateField()

    def save(self, **kwargs):
        u"""insertする直前に主キーの値をつくる"""
        self.id = "%s@%s" % (str(self.held_date), self.name)
        super(Event, self).save(**kwargs)

djangoのsave()を上書きしたとき、マネージャのメソッドでは呼んでくれるのと呼んでくれないのがある

呼んでくれる

  • create
  • get_or_create
  • update_or_create

呼んでくれない

  • bulk_create
    • This does *not* call save() on each of the instances

意外と呼んでくれる。
signals.pre_saveというのもあるが、やってること同じだしsave上書きのほうが明示的で良い。

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?