Home > Mobile >  How to Compare ManyToManyField to another ManyToManyField
How to Compare ManyToManyField to another ManyToManyField

Time:03-26

I have a model of Partner

class Partner(models.Model):
    name = models.CharField(max_length=100, blank=True, null=True)
    group = models.OneToOneField(
        Group, on_delete=models.DO_NOTHING, blank=True, null=True)

    def __str__(self):
        return self.name

I have 2 other models one is CustomUser and other is Quote

class CustomUser(AbstractUser):
    #...
    name = models.CharField(max_length=160, null=True, blank=True)
    partner = models.ManyToManyField(
        Partner, blank=True)

class Quote(models.Model):
    #...
    visibility = models.CharField(max_length=10)
    partner = models.ManyToManyField(
        Partner, blank=True)

Both have a partner field related with ManyToManyField to Partner Model

Now I want to compare them in the views like: partner field can have multiple partners like partner1, partner2, partner3

how to to find the partners matching to each other inside the Quote and CustomUser model

Lets say, One of the Quote object have set of [partner1 and partner6] in the ManyToManyField and I only want to have access to that quote to users who also have partner1 and partner6 in their partner ManyToManyField set.

So how can I filter and compare them ? I also read the docs but didn't able to reproduce the solution. help would be appreciated.

Edit : I can explain it a little , lets say From whole set of partner's in the quote if even one partner is matched to set of partners to the CustomUser then CustomUser should also have access to it.

CodePudding user response:

You can .filter(…) [Django-doc] with:

Quote.objects.filter(partner__customuser=my_user)

This will return a QuerySet of Quotes that have at least one Partner in common with my_user.

The same Quote will be returned that many times as there are Partners in common. You can use .distinct() [Django-doc] to avoid that:

Quote.objects.filter(partner__customuser=my_user).distinct()
  • Related