Home > Net >  Filter queryset only where the user is added to ManyToManyFIeld
Filter queryset only where the user is added to ManyToManyFIeld

Time:12-23

I want to return all leads that contain a current user. How to do it?

Models.py

class CustomUser(AbstractUser):

    def __str__(self):
        return self.email


class Lead(models.Model):
    budget = models.IntegerField()
    buyer = models.ManyToManyField(CustomUser)

What queryset is expected

Lead.objects.filter(buyer__have=request.user)

CodePudding user response:

You can filter with:

Lead.objects.filter(buyer=request.user)

this will make an INNER JOIN, and return only Lead objects where request.user is (one of) the buyers.

  • Related