donkeyboy72
donkeyboy72

Reputation: 1943

Django ManyToManyField Retrieving both objects error

I implemented a ManyToManyField for a following feature which allows users to follow other users and if they follow other user . They would able to retrieve their's objects.

This is my module

 class Person(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=100, blank=True)
    image = models.FileField(upload_to="images/",blank=True)
    following = models.ManyToManyField('self', related_name='followers', symmetrical=False, blank=True, null=True)
    birthday = models.DateField(blank=True,null=True)

    def __unicode__(self):
        return self.name

 class Board(models.Model):

    user = models.ForeignKey(User)
    name = models.CharField(max_length=100)
    created = models.DateTimeField(auto_now_add=True)
    picture = models.OneToOneField('Picture',related_name='picture',blank=True,null=True)
    def __unicode__(self):
        return self.name

The problem is when a user is following 2 users . I am only able to retrieve a single user objects instead of both users.

For example I created 3 users , Jimmy , Sarah and Simon . Sarah is following Simon and Jimmy

Jimmy has a board called Jimmy's Math Board ,Jimmy English Board Simon has a single board called Simon's Whiteboard

The problem is underneath

 >>> from pet.models import *
 >>> from django.contrib.auth.models import User
 >>> user = User.objects.get(username='Sarah')
 >>> person = Person.objects.get(user=user)
 >>> sarah = Person.objects.get(user=user)
 >>> sarah.following.all()  # SARAH IS FOLLOWING JIMMY AND SIMON
 [<Person: Jimmy>, <Person: Simon>]
 >>> users = User.objects.filter(pk__in=sarah.following.all().values_list('user__pk',flat=True))
 >>> users
 [<User: Jimmy>, <User: Simon>] # I'm able to retrieve their users
 >>> board = Board.objects.filter(user=users) # when I search for their boards , I only retrieve a single user . Jimmy's board not Simon
 >>> board
 [<Board: Jimmy's Math Board>, <Board: Jimmy English Board>]
 >>> person = Person.objects.filter(user=users) 
 >>> person
 [<Person: Jimmy>]

How Can I retrieve both of these users board?

Upvotes: 0

Views: 70

Answers (1)

Ngenator
Ngenator

Reputation: 11259

Because board = Board.objects.filter(user=users) is filtering by user it expects one user to be provided. If you were to do something like board = Board.objects.filter(user__in=users) which uses the __in filter, the filtering will correctly use the list of user objects.

You could also use a flat list of id's instead of objects like so board = Board.objects.filter(user__in=sarah.following.all().values_list('user__pk',flat=T‌​rue))

Upvotes: 1

Related Questions