[Answer]-Django models get_or_create integrity error

1👍

The parameters in get_or_create comes in two parts : first part is the exact match of the only instance that must exist, and other variable data has to be found in a parameter named “defaults”

See the documentation https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create :

obj, created = Person.objects.get_or_create(first_name='John', 
    last_name='Lennon', defaults={'birthday': date(1940, 10, 9)})

Not sure what is your unique key here, I’ll just guess it’s voted_by and voted_for, so we have :

vote, created = Vote.objects.get_or_create(
    voted_by = request.user,
    vote_type = vtype.get(field_name),
    defaults = dict(
        voted_for_id = mobj.shared_by_id,
        shared_object_id = oid
      )
    )

0👍

get_or_create returns a tuple.

vote, created = Vote.objects.get_or_create(
    vote_type = vtype.get(field_name),
    voted_by = request.user,
    voted_for_id = mobj.shared_by_id,
    shared_object_id = oid
    )

where created is True or False saying if it created or retrieved from database.

Leave a comment