- [Django]-Django override save for model only in some cases?
- [Django]-Add additional options to Django form select widget
- [Django]-How do Django models work?
6👍
It can be achieved using Model.objects.get_or_create()
Example
obj, created = Person.objects.get_or_create(
first_name='John',
last_name='Lennon',
defaults={'birthday': date(1940, 10, 9)},
)
Any keyword arguments(here first_name and last_name) passed to get_or_create() — except an optional one called defaults — will be used to query in database(find the object) in database.
It returns a tuple, if an object is found, get_or_create() returns a tuple of that object and False.
Note: Same thing can also be achieved using try except
statements
Example:
try:
obj = Person.objects.get(first_name='John', last_name='Lennon')
except Person.DoesNotExist:
obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))
obj.save()
- [Django]-Alowing 'fuzzy' translations in django pages?
- [Django]-Django database query: How to get object by id?
- [Django]-Django Rest JWT login using username or email?
2👍
Looks like in newer versions of Django the save() function does an UPDATE or INSERT by default. See here.
- [Django]-How to duplicate virtualenv
- [Django]-How to get the currently logged in user's id in Django?
- [Django]-How do I do an OR filter in a Django query?
Source:stackexchange.com