2

I'm trying to order by a count of a manyToMany field is there a way to do this with TastyPie?

For example

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

I want PersonResource to spit out json that is ordered by the number of friends a person has...

is that possible?

4

3 回答 3

2

我无法按照 coaxmetal 的解决方案获得结果排序,所以我以不同的方式解决了这个问题,通过根据http://django-tastypie.readthedocs.org/en/latest/cookbook覆盖 Resource 对象上的 get_object_list .html。基本上,如果 'top' 查询字符串参数存在,则返回排序结果。

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
于 2013-06-17T03:46:37.670 回答
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 类的 queryset=... 中添加注释,或者覆盖 get_object_list(self,request) 方法。

于 2012-09-28T17:47:54.450 回答
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])]

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

`

于 2011-11-14T05:01:52.090 回答