0

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)
3
  • Both is same, create method Commented Sep 25, 2021 at 1:21
  • Both are same, mostly I use instance = MODEL.objects.create(**validated_data) Commented Sep 25, 2021 at 1:49
  • Use the built-in Django Rest Framework (so call super().create()) unless you have a good reason to override it. Commented Sep 25, 2021 at 2:05

1 Answer 1

1

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().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.