Houman
Houman

Reputation: 66370

Django: How to check if user has already voted on ManyToManyField?

    class Punch(models.Model):
        ring            = models.ForeignKey(Ring)
        voters           = models.ManyToManyField(settings.AUTH_USER_MODEL)

    class Ring(models.Model):
        category        = xxxx

I have this class with a ManyToManyField.

Each user should be able to vote only once for each punch. Now I need to know if a user has already voted for a particular punch.

How would I do that?

punch.voters.filter(??? = request.user)

Reading the documentation I came up with this:

voters = get_user_model().objects.filter(punch__voters=request.user)

but this gives me the total number of times a user has voted for all punches. But I am interested in one particular punch only, to see if he has voted for that.

I am still struggling to solve this. Thanks for help

Upvotes: 1

Views: 524

Answers (2)

manojlds
manojlds

Reputation: 301297

Can you try this:

punch.voters.filter(pk=request.user.pk)

You can also replace the filter with a try-expect wrapped get

Upvotes: 0

Glyn Jackson
Glyn Jackson

Reputation: 8354

Many-to-many relationships can be queried using lookups across relationships.

Upvotes: 2

Related Questions