Home > Enterprise >  Right way to create nested objects and custom create method
Right way to create nested objects and custom create method

Time:09-26

If I use create method redefinition, which type of create objects should I use? Model.objects.create(...) or super.create(...). Both works as expected. What is best practice?

def create(self, validated_data):
    nested_data = validated_data.pop('nesteds', None)
    # THIS ONE
    instance = MODEL.objects.create(**validated_data)
    # OR THIS
    instance = super().create(validated_data)

CodePudding user response:

You should almost always prefer using super().

Contrary to what the comments mention, both are not the same. super() is a Python's feature which allows you to call a method on the parent class. This is very useful if you have multiple levels of inheritance and each parent class does some additional operations on the data before creating the object.

Also, it helps you avoid writing duplicate code. The object creation logic already exists in the parent class, so there's no purpose in writing it again in the subclass as well. Just call super() and let the parent deal with it.

Of course, there are rare cases when you may not want to execute the parent class's logic. In those cases you should avoid super().

  • Related