Django选择不同的字段不起作用

时间:2012-01-11 19:14:32

标签: python mysql django distinct

我有2个型号:

class Team(models.Model):
        """
        Team model for creating a basic team.
        """
        image = ThumbnailerImageField(upload_to=_profile_image_directory(), verbose_name=u'Logo', help_text=u'Uploading a team logo is highly recommended.', blank=True)
        name = models.CharField(verbose_name=u'Team Name', max_length=100)
        school = models.CharField(verbose_name=u'School Name', max_length=100, blank=True)
        city = models.CharField(max_length=100, blank=True)
        state = USStateField(blank=True)
        description = models.CharField(blank=True, max_length=175)
        members = models.ManyToManyField(User, through='TeamMember')
        key = models.CharField(max_length=8, unique=False, blank=True)
        private = models.BooleanField(blank=True)
        twitter = models.CharField(verbose_name=u'Twitter handle', max_length=15, blank=True)
        hashtag = models.CharField(help_text=u'Tweets containing this hashtag will be pulled into your team\'s Twitter feed', max_length=20, blank=True)

        def __unicode__(self):
                return u'%s' % (self.name)

        class Meta:
                verbose_name = u'Team'
                verbose_name_plural = u'Teams'
                unique_together = ('name', 'school', 'state')

class TeamMember(models.Model):
        """
        Team model for connecting users with teams.
        """
        user = models.ForeignKey(User)
        team = models.ForeignKey(Team)
        number = models.PositiveIntegerField(max_length=3, blank=True, null=True)
        position = models.CharField(max_length=100, blank=True)
        start = models.CharField(help_text=u'Year only. Format: 2004', max_length=4, blank=True)
        end = models.CharField(help_text=u'Year only. Leave blank for current team', max_length=4, blank=True)
        created = models.DateTimeField(auto_now_add=True)
        updated = models.DateTimeField(auto_now=True)

我正在尝试按名称搜索当前用户的所有队友,所以我在这里有一个查询:

TeamMember.objects.filter(team__members=request.user).filter(user__username__icontains=query).exclude(user=request.user)

此查询有效,但如果该用户与您在多个相同的团队中,我会多次获得重复用户,因此我想在用户字段上执行DISTINCT或GROUP BY,但我尝试的所有内容都不起作用

我试过了:

TeamMember.objects.filter(team__members=request.user).filter(user__username__icontains=query).exclude(user=request.user).distinct("user")

这个有用,但是没有给我足够的关于用户的信息,只是他们的id,因为它被转换为dict:

TeamMember.objects.filter(team__members=request.user).filter(user__username__icontains=query).exclude(user=request.user).values("user").distinct()

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您的查询会返回不同的TeamMember,而不是user

为了获得不同的user

user.objects.filter( 
                teammember__team__teammember__user__icontains=query
          ).exclude(user=request.user).distinct()

解释:区分users他们teammember的{​​{1}}与teamteammember的{​​{1}}包含user所有这些除了记录用户。