Question

    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

Was it helpful?

Solution 2

Can you try this:

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

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top