2014-03-29 105 views
2

我有以下型号:复杂的Django模型查询

class Vote(models.Model): 
    voter = models.ForeignKey(User) 
    target = model.ForeignKey(User) 
    timestamp = models.DateTimeField() 
    game = models.ForeignKey(Game) 
    step = model.IntegerField() 
    type = models.ForeignKey(VoteType) 

,我需要选择最投票目标和关系的情况下,选择谁的票最早的目标。是否有可能使用Django ORM?

UPDATE:其实我也在里面投三个领域:gameturntype(我将他们添加到上面的代码),我需要根据前面给定的约束条件来选择赢家特定gameturntype (即类似.filter(game=1, step=2, type=3)

+0

请参阅django模型,https://docs.djangoproject.com/en/dev/topics/db/models/ – WeizhongTu

+0

进行查询https://docs.djangoproject.com/en/dev/topics/db/queries/ – WeizhongTu

回答

3

您可以使用注解来选择由注释字段中的计票和表决最早时间为每个用户,然后才能选择第一:

from django.db.models import Count, Min 

winner = User.objects.annotate(vote_count=Count('vote_set'))\ 
    .annotate(first_vote_time=Min('vote_set__timestamp'))\ 
    .order_by('-vote_count', 'first_vote_time')[0] 

UPDATE: 您可以应用以下过滤器只能算选票特定游戏:

.filter(vote_set__game=game, vote_set__step=step, vote_set__type=type) 

双下划线允许您对相关对象的属性进行筛选。

请务必在注释之前应用过滤器,以便只计算正确的投票数,并确保所有投票的过滤条件都在相同的过滤器调用中。为什么你必须做后者解释here

+0

'vote_set'是指什么? (表格投票?) – Sirion

+0

好的,现在我注意到你正在对用户进行查询,谢谢! – Sirion

+0

不幸的是我看不到如何将这个解决方案扩展到我的实际问题(请参阅我的问题中的更新部分)。 – Sirion