Ahmet DAL Ahmet DAL - 1 year ago 88
Python Question

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
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)})

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!

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download