按条件Django排序

时间:2013-04-05 21:02:43

标签: python sql django sql-order-by django-queryset

我有3个模型userprofile和group:

class UserProfile(models.Model):    
    slug = models.SlugField(max_length=200)
    user = models.ForeignKey(User, unique =True)
    professionalNetwork = models.ForeignKey('SubForum',null=True, blank=True)

class Group(models.Model):
    slug = models.SlugField(max_length=200)
    name = models.CharField(max_length=200)
    professionalNetwork = models.ForeignKey('SubForum')

class SubForum(models.Model):
   name = models.CharField(max_length=200)

我如何获得所有订购的团体,首先是与特定用户具有相同专业网络的团体,然后是其他团体?

我正在研究像Group.objects.all()。order_by(' - professionalNetwork = profile.professionalNetwork')这样的东西,但这当然不起作用^^

谢谢你

2 个答案:

答案 0 :(得分:1)

这个怎么样(类似于docs中的例子)。这个想法是你引入另一个字段来计算该组是否属于指定的专业网络,然后查询集按该字段排序。

subforum_id = 1  # some id here by which you need to sort

sql = ''.join((
    'CASE professionalNetwork ',
    'WHEN {} THEN 1 '.format(subforum_id),
    'ELSE -1',
))
q = Group.objects.extra(select={'same_subforum': sql})
q = q.extra(order_by=['same_subforum'])

答案 1 :(得分:0)

我明白了!

groupRecommendation = Group.objects.extra(
select={
    'network': """
    SELECT COUNT(*) FROM axiom_alto_userprofile
    WHERE \"professionalNetwork_id\"= axiom_alto_group.\"professionalNetwork_id\" AND axiom_alto_userprofile.id = %d """ % profile.id, 
},
).order_by('-network')

这给了我1个拥有相同专业网络的团队,0个给那个没有的人^^