2011-11-14 49 views
2

我想通过计数manyToMany字段来订购有没有办法用TastyPie做到这一点?是否可以通过django TastyPie的注释进行排序?

例如

class Person(models.Model): 
    friends = models.ManyToMany(User, ..) 

我想PersonResource吐出由朋友一个人数量排序JSON ...

这可能吗?

+0

您是否找到任何解决方案?我也有同样的问题。 – Burak

回答

0

我没有使用过TastyPie,但你的问题似乎更一般。您不能在Django ORM查询中进行自定义排序。你最好存储表单的元组(Person,friend_count)。这是很简单的:

p_list = [] 
for person in Person.objects.all(): 
    friendcount = len(person.friends.all()) 
    p_list.append((person, friendcount)) 

然后,您可以使用内置的sorted功能,像这样:

sorted_list = [person for (person, fc) in sorted(p_list, key=lambda x: x[1])]

最后一行基本上是从人的排序列表中提取的人,上排序一个朋友没有。

`

2

我知道这是一个老问题,但最近我遇到了这个问题,并解决了上来。

Tastypie不容易自定义排序,但很容易修改它使用的查询集。 我其实刚刚使用自定义管理器修改了模型的默认查询集。

例如:

class PersonManager(models.Manager): 
    def get_query_set(self): 
     return super(PersonManager self).get_query_set().\ 
      annotate(friend_count=models.Count('friends')) 

class Person(models.Model): 
    objects = PersonManager() 
    friends = ... 

您还可以添加注释在Tastypie,在查询集枯萎= ...在Meta类,或者重写get_object_list(个体经营,request)方法。

2

我无法按照coaxmetal的解决方案获得结果排序,所以我通过覆盖Resource对象上的get_object_list按照http://django-tastypie.readthedocs.org/en/latest/cookbook.html来解决这个问题。基本上,如果'top'querystring参数存在,那么返回有序的结果。

class MyResource(ModelResource): 
    class Meta: 
     queryset = MyObject.objects.all() 

    def get_object_list(self, request): 
     try: 
      most_popular = request.GET['top'] 
      result = super(MyResource, self).get_object_list(request).annotate(num_something=Count('something')).order_by('num_something') 
     except: 
      result = super(MyResource, self).get_object_list(request) 
     return result 
相关问题