2013-01-01 14 views
59

Voglio creare un oggetto modello, come Persona, se l'ID della persona non esiste, o otterrò quell'oggetto persona.Crea modello Django o aggiorna se esiste

il codice per creare una nuova persona come segue:

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 

Ma non so dove per controllare e ottenere l'oggetto persona esistente.

risposta

111

Se siete alla ricerca di "aggiornamento se esiste altro creare" caso d'uso, si prega di fare riferimento al @Zags excellent answer


Django ha già un get_or_create, https://docs.djangoproject.com/en/1.9/ref/models/querysets/#get-or-create

Per voi potrebbe essere:

+0

sto usando Django 1.9, e mi sta dando: AttributeError: oggetto 'QuerySet' non ha alcun attributo 'update_or_create' –

+0

@OfekGila È strano, sia il [codice sorgente] (https://github.com/django /django/blob/master/django/db/models/query.py#L475) e la [documentazione] (https://docs.djangoproject.com/en/1.9/ref/models/querysets/#update-or- create) conferma 'QuerySet' ha' update_or_create' – bakkal

3

Ho pensato di aggiungere una risposta dal momento che il titolo della domanda sembra chiedere come creare o aggiornare, piuttosto che ottenere o creare come descritto nel corpo della domanda.

Se avete voglia di creare o aggiornare un oggetto, il .save() metodo ha già questo comportamento di default, da the docs:

Django abstracts the need to use INSERT or UPDATE SQL statements. Specifically, when you call save(), Django follows this algorithm:

If the object’s primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes an UPDATE. If the object’s primary key attribute is not set or if the UPDATE didn’t update anything, Django executes an INSERT.

Vale la pena notare che quando dicono 'se il didn UPDATE 'aggiorna qualcosa' si riferiscono essenzialmente al caso in cui l'id che hai fornito all'oggetto non esiste già nel database.

73

Non è chiaro se la tua domanda è chiedere il metodo get_or_create (disponibile almeno da Django 1.3) o il metodo update_or_create (nuovo in Django 1.7). Dipende da come si desidera aggiornare l'oggetto utente.

utilizzo esempio è la seguente:

# 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} 
) 
+5

+1 per 'update_or_create' perché per quel caso d'uso è meglio di' get_or_create' solo per chiamare di nuovo 'save()' sull'oggetto. – bakkal

0

Se uno degli ingressi quando si crea è una chiave primaria, questo sarà sufficiente:

Person.objects.get_or_create(id=1) 

Si aggiornerà automaticamente se esiste dal momento che due i dati con la stessa chiave primaria non sono consentiti.