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)
, whereobject
is the retrieved or created object andcreated
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))
- [Django]-Cannot import ASGI_APPLICATION module 'myproject.routing'
- [Django]-Process field before database insert / update
- [Django]-How can I set arbitrary attributes on Django Model Fields, then access them in a ModelForm?
- [Django]-Parsing dates with django utils parse_date
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)
, whereobject
is the retrieved or created object andcreated
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.
- [Django]-Django Humanize naturaltime templatetag only partly translating
- [Django]-Django admin list_display foreign key id without join
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.
- [Django]-DateTime in ISO 8601 + TimeZone and without microseconds
- [Django]-Access Django App on AWS ec2 host