whatf
whatf

Reputation: 6468

django models get_or_create integrity error

I have a model as follows:

class Vote(models.Model):

    vote_type = models.BooleanField()
    voted_by =  models.ForeignKey(User, related_name='voted_by')
    voted_for = models.OneToOneField(User, related_name='voted_for')
    article = models.ForeignKey(Article, null=True, blank=True)
    dtobject  = models.DateTimeField(auto_now_add=True)

I want to make sure that a user can vote for an object only once. Hence in my views I do the following:

    v = Vote.objects.get_or_create(
        vote_type = vtype.get(field_name),
        voted_by_id = request.user.id,
        voted_for_id = mobj.shared_by_id,
        shared_object_id = oid
        )

It works fine for the first time, but when there is already an existing vote, i get an integrity error, reasons are obvious. Given the above model and views, what would be a good approach to ensure that the object has not been voted?

Upvotes: 0

Views: 1805

Answers (2)

vincent
vincent

Reputation: 6618

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
      )
    )

Upvotes: 1

Rag Sagar
Rag Sagar

Reputation: 2374

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.

Upvotes: 0

Related Questions