Django - Overriding the Model.create() method?

后端 未结 7 956
忘了有多久
忘了有多久 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:32

    This is old, has an accepted answer that works (Zach's), and a more idiomatic one too (Michael Bylstra's), but since it's still the first result on Google most people see, I think we need a more best-practices modern-django style answer here:

    from django.db.models.signals import post_save
    
    class MyModel(models.Model):
        # ...
        @classmethod
        def post_create(cls, sender, instance, created, *args, **kwargs):
            if not created:
                return
            # ...what needs to happen on create
    
    post_save.connect(MyModel.post_create, sender=MyModel)
    

    The point is this:

    1. use signals (read more here in the official docs)
    2. use a method for nice namespacing (if it makes sense) ...and I marked it as @classmethod instead of @staticmethod because most likely you'll end up needing to refer static class members in the code

    Even cleaner would be if core Django would have an actual post_create signal. (Imho if you need to pass a boolean arg to change behavior of a method, that should be 2 methods.)

提交回复
热议问题