0

Using Django, I have 2 models.

Model1 -> User
          -> ID
          -> Some properties

Model2 -> Activeness
          -> UserId (Foreign Key to User)
          ->rating

This is a simplified case. I am trying to get a list of users sorted by their rating in the activeness table. User.objects.all().order_by('activeness__rating')

This works ok.

However, I have some situations where the activeness object for new users has not been created yet. This will result in those new users appearing at the top of the list obtained. I want them to appear at the bottom of the list instead.

I can't resort in python because I am using paging and retrieving 1 page at a time.

Can anyone advise. Thanks.

4

2 回答 2

1

您是否尝试过使用注释?它可能会有所帮助

使用注释,你可以做这样的事情

User.objects.all().annotate(num_rating=Count('activeness__rating')).order_by('num_rating')

我希望它有帮助

于 2012-10-10T07:26:42.063 回答
1

TLDR:过滤掉activeness为空的用户对象,稍后再添加。

长版:给定一些模型,例如

class MyUser(models.Model):
    activeness = models.ForeignKey('Activeness', null=True)
    name = models.CharField(max_length=50)

    def __unicode__(self):
        return "{}: {}".format(self.name, self.activeness.rating if self.activeness else "no rating")

class Activeness(models.Model):
    rating = models.FloatField()

和一些像这样的样本数据

<MyUser: Bob: 3.62810036125>,
<MyUser: Tim: no rating>,
<MyUser: Jim: 2.41014167534>,
<MyUser: Rod: 1.35651839383>]

您可以排除没有评分的用户,如下所示:

>>> MyUser.objects.filter(activeness__rating__isnull=False).order_by('activeness__rating')
[<MyUser: Rod: 1.35651839383>, <MyUser: Jim: 2.41014167534>, <MyUser: Bob: 3.62810036125>]

然后将它们附加到末尾,您可以使用以下命令提高效率chain() from itertools

>>> from itertools import chain
>>> chain(MyUser.objects.filter(activeness__rating__isnull=False).order_by('activeness__rating'), MyUser.objects.filter(activeness__rating__isnull=True))
[<MyUser: Rod: 1.35651839383>,
 <MyUser: Jim: 2.41014167534>,
 <MyUser: Bob: 3.62810036125>,
 <MyUser: Tim: no rating>]

例如,如果我们进行调试,我们可以看到这可以防止查询集被毫无意义地评估。

>>> from django.db import connection
>>> import pprint
>>> connection.queries = []
>>> for u in chain(MyUser.objects.filter(activeness__rating__isnull=False).order_by('activeness__rating').select_related('activeness'), MyUser.objects.filter(activeness__rating__isnull=True)):
>>>     print "At {u} we've done {count} SQL queries".format(u=u, count=len(connection.queries))
At Rod: 1.35651839383 we've done 1 SQL queries
At Jim: 2.41014167534 we've done 1 SQL queries
At Bob: 3.62810036125 we've done 1 SQL queries
At Tim: no rating we've done 2 SQL queries

当然,你仍然需要做更多的工作才能让它与Django paginator一起工作,但这超出了这个问题的范围。

于 2012-10-10T08:20:03.220 回答