Django ManyToManyField检索两个对象错误

时间:2013-03-24 02:25:03

标签: django django-models

我为以下功能实现了ManyToManyField,允许用户关注其他用户,如果他们关注其他用户。 他们能够检索他们的对象。

这是我的模块

 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

问题是当用户关注2个用户时。我只能检索单个用户对象而不是两个用户。

例如,我创建了3个用户,Jimmy,Sarah和Simon。莎拉跟随西蒙和吉米

Jimmy有一个名为Jimmy's Math Board的董事会,Jimmy English Board Simon有一块名为Simon's Whiteboard的单板

问题出在

之下
 >>> 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>]

如何检索这两个用户板?

1 个答案:

答案 0 :(得分:1)

由于board = Board.objects.filter(user=users)user过滤,因此需要提供一个用户。如果您要执行使用board = Board.objects.filter(user__in=users)过滤器的__in之类的操作,过滤将正确使用用户对象列表。

你也可以使用id的平面列表而不是像board = Board.objects.filter(user__in=sarah.following.all().values_list('user__pk',flat=T‌​rue))这样的对象