user1687717 user1687717 - 1 year ago 341
Python Question

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.

Answer Source

Django has some convenient built-ins so you don't have to do it yourself

get_or_create(defaults=None, **kwargs)

For you it could be :

person, created = Person.objects.get_or_create(
     identifier='some identifier',
     defaults={'name': 'Robert'},

if created:
   # means you have created a new person
   # person just refers to the existing one

If you're looking for "update if exists else create" use case, please refer to @Zags excellent answer

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