'How to query and append a list of users emails linked with a manytomany relation to other Model
First please take a look on the data structure. there are Three models
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)
class CustomUser(AbstractUser):
email = models.EmailField(_('email address'), unique=True)
partner = models.ManyToManyField(
Partner, blank=True)
class Quote(models.Model):
partner = models.ManyToManyField(
Partner, blank=True, related_name='quote_partners')
There can be multiple partners inside the Quote and CustomUser partner field. I want to make a list of users email who are linked with Partner inside the partner field set in the quote model. This is how I'm doing;
quote = Quote.objects.get(id=id)
partners = quote.partner.all()
for partner in partners:
recipient_list = []
for user in CustomUser.objects.filter(groups__partner=partner):
recipient_list.append(user.email)
Currently quote object has 3 partners and collectively 4 users linked to these partners then there should be 4 emails in the the recipient_list, But this returning empty array []. Please highlight what I'm doing wrong and how to fix it.
Solution 1:[1]
You can .filter(…) [Django-doc] with:
CustomUser.objects.filter(groups__partner__quote_partners__id=id)
This looks for CustomUsers linked to a Group linked to a Partner linked to a Quote with the given id.
You can query with:
CustomUser.objects.filter(partner__quote_partners__id=id)
To look for CustomUsers that have a related Partner that has a related Quote with id as primary key.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
