如何使用来自不同查询的分组值连接一个表?

时间:2014-07-26 12:29:11

标签: django django-models

我有这样的模特:

class Subscription(models.Model):
    visable_name = models.CharField(max_length=50, unique=True)

    recipe_name = models.CharField(max_length=50)
    website_url = models.URLField()


class User(models.Model):
    username = models.CharField(max_length=50)


class UserSubs(models.Model):
    subscription = models.ForeignKey(Subscription, to_field='visable_name')
    user = models.ForeignKey(User, to_field='username')

我想准备简单的排名,所以我想出了类似的东西:

rank = UserSubs.objects.values('subscription').
                        annotate(total=Count('user')).
                        order_by('-total')`

是什么赋予:

>> rank
[
   {'total': 3, 'subscription': u'onet'}, 
   {'total': 2, 'subscription': u'niebezpiecznik'}, 
   {'total': 1, 'subscription': u'gazeta'}
]

我需要的是类似的完整对象列表:

[
   {'total': 3, 'subscription': <Subscription: onet>}, 
   {'total': 2, 'subscription': <Subscription: niebezpiecznik>}, 
   {'total': 1, 'subscription': <Subscription: gazeta>}
]

我不确定,是否选择了相关的&#39;在这里会有所帮助,但我无法弄清楚如何使用它:(

2 个答案:

答案 0 :(得分:2)

最好从Subscription构建您的查询,因为您需要它:

Subscription.objects.annotate(total=models.Count('usersubs')).order_by('-total')

答案 1 :(得分:1)

也许你可以使用dict和list comprehension,并将其过滤为简单的python对象:

d = {sub.visable_name: sub for sub in Subscriptions.objects.all()}
new_rank = [
  {
    'total': row['total'], 
    'subscriptions': d[row['subscriptions']]
  } 
  for row in rank
]

会给出什么:

>> new_rank
[
  {'total': 3, 'subscriptions': <Subscriptions: onet>}, 
  {'total': 2, 'subscriptions': <Subscriptions: niebezpiecznik>}, 
  {'total': 1, 'subscriptions': <Subscriptions: gazeta.pl>}
]