Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get list of objects involving many to many relation in django

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?

like image 653
Atma Avatar asked Sep 15 '13 19:09

Atma


People also ask

How fetch data from many-to-many field in Django?

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.

What is objects all () Django?

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.


1 Answers

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

like image 95
karthikr Avatar answered Oct 09 '22 22:10

karthikr