Opened 13 years ago

Closed 13 years ago

#5662 closed (invalid)

get_or_create fails when there is a unique field and other values

Reported by: kenneth gonsalves <lawgon@…> Owned by: nobody
Component: Database layer (models, ORM) Version: master
Severity: Keywords: get_or_create
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


This is for svn head and postgresql backend. Assume a model like this:

class Word(models.Model):
    english=models.CharField(_("English Meaning"),maxlength=500)

I want to dump values from some external source into this table using get_or_create. If the 'word' exists, the no action should be taken, otherwise the row has to be created. If i make my query like this:

a,b = Word.objects.get_or_create(word=wd, language=lng,rootword=rtwd, english=eng)

then unless *all* the fields match in the existing row, django assumes that the row does not exist and attempts to create the row which results in a duplicate key error in postgresql. As a result, the query has to be restricted to 'word' only, to avoid the duplicate key error. If the row containing 'word' is got, then the row has to be updated with the remaining values. If it is created - again it needs to be updated with the remaining values. This could be solved with an update_or_create query?

Change History (3)

comment:1 Changed 13 years ago by Jonathan Buchanan

Isn't this why the defaults argument exists?

word, created = Word.objects.get_or_create(word=wd, defaults=dict(language=lng, rootword=rtwd, english=eng))

comment:2 Changed 13 years ago by Nis Jørgensen <nis@…>

Just for reference, the syntax for using the defaults argument would be

word, created = Word.objects.get_or_create(word=wd, defaults=dict('language':lng, 'rootword': rtwd, 'english':eng))

comment:3 Changed 13 years ago by James Bennett

Resolution: invalid
Status: newclosed

This is pretty much why defaults exists.

Note: See TracTickets for help on using tickets.
Back to Top