1
我有2種型號:Django的選擇不同領域的工作不
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,因爲它被轉換成一個字典:
TeamMember.objects.filter(team__members=request.user).filter(user__username__icontains=query).exclude(user=request.user).values("user").distinct()
有什麼想法嗎?
我的回答有助於解決您的問題?我可以改進它嗎?讓我知道如果這是一個錯誤的答案,以解決它。 – danihp 2012-01-13 20:46:54