How to use get_or_create in Python Django?

Published On: 10/08/2022 | Category: Django

Hi Dev,

This is a short guide on django get_or_create example. we will help you to give example of get_or_create in django. it's simple example of django get_or_create defaults. you will learn django get_or_create example tutorial. follow bellow step for how to use get_or_create query in django.

We can use the get_or_create() method to check the existence of an object and creates an object based upon its existence. This method has 2 parameters, first is “defaults” which are used to set default values for fields.

And second is “kwargs” which is used to define keyword arguments. And this method checks the object based upon the “kwargs” argument.

Here i explained simply step by step django get_or_create example:

Example : 1

In this example, we are using the get_or_create() method to create or retrieve an object, based upon the given firstname and lastname values. Now, if the object is already there in the database then, it will return a tuple as (object_name, False). Where object_name is the name of the object and False represents objects is not created.

python manage.py shell

Now, we will execute the following example.

>>> 
>>> from myApp.models import Employee
>>> 
q = Employee.objects.get_or_create(
    firstname='Bhavesh',
    lastname='Sonagra'
    
)
>>> print(q)
Output
(<Employee: Employee object (1)>, False)
Example : 2

In this second example unable to retrieve the object with given arguments then, it will create a new object with given values. And after creation, it will return the object name and True in the tuple. Let’s have an example of creating a new object using the get_or_create() method.

python manage.py shell

Now, we will execute the following example.

>>> 
>>> from myApp.models import Employee
>>> 
q = Employee.objects.get_or_create(
    firstname='Vishal',
    lastname='Patel'
    
)
>>> print(q)
Output
(<Employee: Employee object (2)>, False)

I Hope It will help you....