Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django save or update model

I am using Django 1.5.1 and I want to save or update model.

I read the django document and I met the get_or_create method which provides saving or updating. There is a usage like;

Model.objects.get_or_create(name='firstName',surname='lastName',defaults={'birthday': date(1990, 9, 21)})

defaults field is using only for getting. While it is setting phase, name and surname are only set. That is what I understand from the document.

So I want to do something different that setting name,surname and birthDay, but getting name and surname excluding birthdate. I could not see the way to do that in the document and another place.

How can I do this?

Thank you!

like image 947
Ahmet DAL Avatar asked Jan 29 '26 20:01

Ahmet DAL


2 Answers

get_or_create provides a way of getting or creating. Not saving or updating. Its idea is: I want to get a model, and if it doesn't exist, I want to create it and get it.

In Django, you don't have to worry about getting the name or the surname or any attribute. You get an instance of the model which has all the attributes, I.e.

instance = Model.objects.get(name='firstName',surname='lastName')

print instance.birthday
print instance.name
print instance.surname

An overview of the idea could be: a Model is a data structure with a set of attributes, an instance is a particular instance of a model (uniquely identified by a primary_key (pk), a number) which has a specific set of attributes (e.g. name="firstName").

Model.objects.get is used to go to the database and retrieve a specific instance with a specific attribute or set of attributes.

like image 132
Jorge Leitao Avatar answered Jan 31 '26 08:01

Jorge Leitao


Since Django 1.7 there's update_or_create:

obj, created = Person.objects.update_or_create(
    first_name='John',
    last_name='Lennon',
    defaults=updated_values
)

The parameters you give are the ones that will be used to find an existing object, the defaults are the parameters that will be updated on that existing or newly created object.

A tuple is returned, obj is the created or updated object and created is a boolean specifying whether a new object was created.

Docs: https://docs.djangoproject.com/en/1.8/ref/models/querysets/#update-or-create

like image 31
gitaarik Avatar answered Jan 31 '26 08:01

gitaarik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!