简体   繁体   中英

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!

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, Ie

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 (eg 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM