Post Image

Django Get Database Record or Create if it Doesn't Exist

When interacting with a database often times you need to check if there is a database record matching the data you are processing, if it exists you want the record, if it does not exist, you want to create the record. Django provides an integrated way of handling this for you so you don't have to do it yourself. In this post I will demonstrate the get or create method in Django.

 

Database Model

For this example we will assume the model you are working with is below

class User(models.Model):
    
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    description = models.CharField(max_length=1000)

 

get_or_create

Because our model inherits from models.Model we automatically have the base functionality of get or create in the appropriately named get_or_create method. Below is an example of using it to get a database record and creating it if it doesn't exist.

first_name = 'Robert'
last_name = 'Paul'

db_object, was_created = User.objects.get_or_create(first_name=first_name, last_name=last_name, defaults={'description': 'Default Description'})

 

Stepping through this we have a first and last name that we are looking for.

We then use the get_or_create method on the model objects attribute.

I pass in the first and last name as keyword arguments which is what will be used to filter a database object if one exists.

I also pass in a keyward argument defaults which I pass in a dictionary of default values I would like the object to have if it does not exist.

Lastly that method returns 2 objects, the database object, and a boolean if the record was created or not.

 

 

If you would like to read the official documentation on get_or_create, I have a link to it here.

 

 

 



Comments (0)
Leave a Comment