Django - Overriding the Model.create() method?

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

    To answer the question literally, the create method in a model's manager is a standard way to create new objects in Django. To override, do something like

    from django.db import models
    
    class MyModelManager(models.Manager):
        def create(self, **obj_data):
            # Do some extra stuff here on the submitted data before saving...
            # For example...
            obj_data['my_field'] = my_computed_value(obj_data['my_other_field'])
    
            # Now call the super method which does the actual creation
            return super().create(**obj_data) # Python 3 syntax!!
    
    class MyModel(models.model):
        # An example model
        my_field = models.CharField(max_length=250)
        my_other_field = models.CharField(max_length=250)
    
        objects = MyModelManager()
    

    In this example, I'm overriding the Manager's method create method to do some extra processing before the instance is actually created.

    NOTE: Code like

    my_new_instance = MyModel.objects.create(my_field='my_field value')

    will execute this modified create method, but code like

    my_new_unsaved_instance = MyModel(my_field='my_field value')

    will not.

提交回复
热议问题