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.
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.
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.
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} )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With