假设我有一个返回10名对象,其中3将显示在下面的位置的查询集:伪随机排序查询集
[ display 1 position ] [ display 2 position ] [ display 3 position ]
该模型代表它如下:
class FeaturedContent(models.Model):
image = models.URLField()
position = models.PositiveSmallIntegerField(blank=True, null=True)
其中位置可以是1,2,3或未指定(Null)。
我想能够随机订购QuerySet EXCEPT对于具有指定位置的对象。但是,我不能这样做责令:
featured_content = FeaturedContent.objects.order_by('-position', '?')
因为如果我有一个项目是有position = 2
,和其他所有项目都Null
,那么该项目将出现在位置1,而不是位置2
我该如何做这个订购?
思考这一点,也许这将是最好有数据作为一个字典,而不是一个列表,像:
`{'1': item or null, '2': item or null, '3': item or null, '?': [list of other items]}`
你应该真正避免在数据库中进行随机排序(还有[django文档](https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by)指出),因为它往往是真正的慢! –
那么有什么更好的方式来做我需要做的以上? – David542