django模型对象的总和和相关模型的模型字段列表

时间:2013-04-04 11:35:02

标签: django django-models django-views

我需要的是查询,它将返回按编号排序的文章列表,该列表计算为文章对象的foos.all + bar.peaces的总和。以下是模型的外观:

class Article(models.Model):
    name = models.CharField(max_length=150)
    date = models.DateTimeField()
    ...

class Foo(models.Model):
    article = models.ForeignKey(Article, related_name='foos')
    user = models.ForeignKey(User, related_name='userfoos')
    ...

class Bar(models.Model):
    article = models.OneToOneField(Article)
    peaces = models.IntegerField(default=0)
    ...

因此,请说X是文章对象:

foo_num = Foo.objects.filter(article=X).count()
bar_num = Bar.objects.get(article=X)
bar_num = bar_num.peaces
Y = bar_num + foo_num

所以我需要一个按Y

排序的清单列表

1 个答案:

答案 0 :(得分:1)

我会定义自己的排序方法:

def article_sort(article_object):
     return len(article_object.foos.all()) + article_object.bar.peaces

def view():
    articles = sorted(Article.objects.all(), key=article_sort)

更多信息here