Home > database >  What does django's Manager.create() method do?
What does django's Manager.create() method do?

Time:11-19

I was poking around in the rest_framework trying to figure out how it works, and came across a call to Model.objects.create(), but I can't for the life of me find the create() method for django model managers in the docs or the source code. It looks to be dynamically generated. What does it do, exactly? Where can I find its code? If I wanted to override it, what would my implementation have to do? I found this question but it only says to call the super().create() method.

CodePudding user response:

Django's manager will look for the same method on a QuerySet in case that method does not exists in the Manager. So it will call the .create() method [Django-doc] on the underlying QuerySet, which is implemented as [GitHub]:

def create(self, **kwargs):
    """
    Create a new object with the given kwargs, saving it to the database
    and returning the created object.
    """
    obj = self.model(**kwargs)
    self._for_write = True
    obj.save(force_insert=True, using=self.db)
    return obj

It will thus create a model object with the passed keywords, and save it with force_insert=True to slightly improve efficiency, and return the item created at the database.

  • Related