Create Objects Django.How

Author avatar wrote on 02/06/2022

Using save

p1 = Person(first_name="Vuyisile", last_name="Ndlovu")
p1.save()


Using save example with try

try:
p1 = Person(first_name="Vuyisile", last_name="Ndlovu")
p1.save()
messages.success(request, "Company info has been updated." )
except Exception as e:
print("Exception Update Company info ==========================")
print(e)
messages.error(request, "Error. Something went wrong.")
print("End of Exception ==========================")

Using create

Person.objects.create(first_name="Vuyisile", last_name="Ndlovu", title="Benevolent Dictator")

Update or create

obj, created = MyModel.objects.update_or_create(pk=some_value,defaults={'field1':'some value'})

Another example

CompanyPriceException.objects.update_or_create(company=company, language_from=record.language_from, workflow=record.workflow,
language_to=record.language_to, country=record.country, service=record.service,
defaults={'price':record.price, 'max_discount':record.max_discount},)

Get or create

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()
# or (returns a tuple; the object and boolean created status)
obj, created = Person.objects.get_or_create(
first_name='John',
last_name='Lennon',
defaults={'birthday': date(1940, 10, 9)},
)

Bulk create

Category.objects.bulk_create(
[Category(name="Business"),
Category(name="Marketing"),
Category(name="Development")]
)

bulk_update()

objs = [
Entry.objects.create(headline='Entry 1'),
Entry.objects.create(headline='Entry 2'),
]
objs[0].headline = 'This is entry 1'
objs[1].headline = 'This is entry 2'
Entry.objects.bulk_update(objs, ['headline'])

Create an object for a Django model with a many to many field

sample_object = Sample()
sample_object.save()

sample_object.users.add(1,2)
# or
list_of_users = DestinationRate.objects.all()
sample_object.users.set(list_of_users)

We stand with Ukraine