【发布时间】:2018-02-15 11:41:30
【问题描述】:
我有一个 Post 模型:
class Post(models.Model):
headline = models.CharField(max_length=255)
...
我没有成功地试图实现的是获得两个随机组,每组 5 个帖子,其中第二组记录了第一组没有的帖子。
现在我知道如何使用 Python 做到这一点,但我想知道是否有更优雅、类似 ORM 的解决方案。
我尝试了以下方法:
posts = Post.objects.all().order_by('?')
first_group = posts[:5]
second_group = posts[5:]
但这有时会在两个组中返回相同的帖子。
我还试图欺骗系统执行以下操作:
posts = Post.objects.all().order_by('?')
first_group = posts[:5]
second_group = Post.objects.exclude(id__in=first_group)
但还是没有运气。
谁能给我一些指示,这样我就不必在纯 Python 中循环记录?
【问题讨论】:
标签: python django django-orm