I have the following models:
class Committee(models.Model):
customer = models.ForeignKey(Customer, related_name="committees")
name = models.CharField(max_length=255)
members = models.ManyToManyField(member, through=CommitteeMember, related_name="committees")
items = models.ManyToManyField(Item, related_name="committees", blank=True)
class CommitteeRole(models.Model):
committee = models.ForeignKey('Committee')
member = models.ForeignKey(member)
#user is the members user/user number
user = models.ForeignKey(User)
role = models.IntegerField(choices=ROLES, default=0)
class Member(models.Model):
customer = models.ForeignKey(Customer, related_name='members')
name = models.CharField(max_length=255)
class Item(models.Model):
customer = models.ForeignKey(Customer, related_name="items")
name = models.CharField(max_length=255)
class Customer(models.Model):
user = models.OneToOneField(User, related_name="customer")
name = models.CharField(max_length=255)
I need to get all of the Items that belong to all of the commitees in which a user is connected through the CommitteeRole
.
Something like this:
committee_relations = CommitteeRole.objects.filter(user=request.user)
item_list = Item.objects.filter(committees=committee_relations__committee)
How can I accomplish this?
A ManyToManyField in Django is a field that allows multiple objects to be stored. This is useful and applicable for things such as shopping carts, where a user can buy multiple products. To add an item to a ManyToManyField, we can use the add() function.
The Manager is the main source of QuerySets for a model. For example, Blog.objects.all() returns a QuerySet that contains all Blog objects in the database.
Actually, you have already accomplished it (Almost):
committee_relations = CommitteeRole.objects.filter(user=request.user).values_list('committee__pk', flat=True)
item_list = Item.objects.filter(committees__in=committee_relations)
And, if you are looking for a single query, you can try this:
items = Item.objects.filter(customer__committees__committeerole__user=request.user)
Documentation here and here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With