Django tip: How to use get_or_create

/ #Django


The built-in function "get_or_create" is a little gem. In this post you will learn how to use it.

What does it do?

First it will check if an objects exist based on a set of parameters (like primary key or slug). It Django can't find the object in the database, it will create the object for you.

An example

def post_detail(request, post_id):
    post, created = Post.objects.get_or_create(pk=post_id)

    print(created)

    return render(request, 'template.html')

You probably noticed that I have to variables in front of the function call. This is because "get_or_create" actually returns a tuple.

The tuple contains the object + a boolean variable telling you if the object was created or not.

If you visit a post for the first time, the object will be created in the database, but the next time you visit the same page, Django will get it from the database instead.

Comments

No comments yet...

Add comment

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.