我正在尝试按 ManyToMany 字段的计数进行排序,有没有办法使用 TastyPie 执行此操作?
例如
class Person(models.Model):
friends = models.ManyToMany(User, ..)
我希望 PersonResource 吐出按一个人拥有的 friend 数量排序的 json...
这可能吗?
最佳答案
我知道这是一个老问题,但我最近遇到了这个问题并提出了解决方案。
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) 方法。
关于django - 是否可以通过 django TastyPie 的注释进行订购?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8116950/