0

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

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

4

1 回答 1

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)

更多信息在这里

于 2013-04-04T11:45:15.440 回答