[Django]-Why do we write [0] after get_or_create in model_name.object.get_or_create() in django

5👍

get_or_create() is a queryset method, which returns a tuple (d, created). where d is the model instance and created is boolean flag which tells us if the object is created or not.

so by getting the first index like this

Department.objects.get_or_create(dept_name=random.choice(depatment))[0]

You are actually doing (d, created)[0] which always returns the object. A better way to do this is to use underscore (_) to ignore created flag, like this:

d, _ = Department.objects.get_or_create(dept_name=random.choice(depatment))

reference: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#get-or-create

1👍

This is because get_or_create returns a tuple and you’re usually only interested in the gotten or created object (first element) and not the boolean indicating if the object was just created (second element).

From the documentation on get_or_create:

Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.

Though you can also use the syntax:

def add_dept():
    d, _ = Department.objects.get_or_create(dept_name=random.choice(depatment))

1👍

Because .get_or_create(…) [Django-doc] return a 2-tuple where the first item is the Department object that is constructed or obtained, and the second is a boolean (True or False) that is True if the object was constructed, as specified in the documentation:

Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.

By adding [0], you thus obtain the first item of the 2-tuple: the department, and thus discard the boolean.

0👍

The function you’re calling returns a list or a tuple. In either case, the [0] simply extracts the first element from the result, and throws any remaining results away.

Leave a comment