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一起工作,但这超出了这个问题的范围。