Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Django model or update if exists

I want to create a model object, like Person, if person's id doesn't not exist, or I will get that person object.

The code to create a new person as following:

class Person(models.Model):     identifier = models.CharField(max_length = 10)     name = models.CharField(max_length = 20)     objects = PersonManager()  class PersonManager(models.Manager):     def create_person(self, identifier):         person = self.create(identifier = identifier)         return person 

But I don't know where to check and get the existing person object.

like image 603
user1687717 Avatar asked Jan 01 '13 23:01

user1687717


People also ask

How do I update model fields in Django?

You specify the fields that should be updated by passing the update_fields keyword argument to the . save() method containing a list of field names. Of course Django provides excellent docs on this particular feature.

How do you add a new field to a model with new Django migrations?

To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB.


1 Answers

It's unclear whether your question is asking for the get_or_create method (available from at least Django 1.3) or the update_or_create method (new in Django 1.7). It depends on how you want to update the user object.

Sample use is as follows:

# In both cases, the call will get a person object with matching # identifier or create one if none exists; if a person is created, # it will be created with name equal to the value in `name`.  # In this case, if the Person already exists, its existing name is preserved person, created = Person.objects.get_or_create(         identifier=identifier, defaults={"name": name} )  # In this case, if the Person already exists, its name is updated person, created = Person.objects.update_or_create(         identifier=identifier, defaults={"name": name} ) 
like image 92
Zags Avatar answered Oct 25 '22 00:10

Zags