我的网站上的每个用户都有一个模型(UserProfile),每个配置文件都包含一个名为points的字段.
我希望在按点排序时从当前用户获得-5 + 5个用户.我怎么能做到这一点?
您可以进行两次查询,一次针对当前用户之前的用户,另一次针对当前用户之后的用户:
id = current_user.pk
points = current_user.profile.points
before = User.objects.filter(
Q(profile__points__gt=points) |
Q(profile__points=points, pk__lt=id)
).order_by('-profile__points')[:5]
after = User.objects.filter(
Q(profile__points__lt=points) |
Q(profile__points=points, pk__gt=id)
).order_by('profile__points')[:5]
Run Code Online (Sandbox Code Playgroud)
这是基于两个查询:
pk。pk。然后通过正确的排序和限制,您可以获得结果。当然pk可以用任何其他字段替换,或者干脆完全删除。在后一种情况下,您可以考虑当前用户始终是第一个(这只是一个示例),并且查询变为:
before = User.objects.filter(
profile__points__gt=points,
).order_by('-profile__points')[:5]
after = User.objects.filter(
profile__points__lte=points,
).exclude(pk=id).order_by('profile__points')[:5]
Run Code Online (Sandbox Code Playgroud)
或者,要仅获取按点排序的用户列表中当前用户的索引,您可以执行以下操作:
id = current_user.pk
points = current_user.profile.points
index = User.objects.filter(
Q(profile__points__gt=points) |
Q(profile__points=points, pk__lt=id)
).count()
Run Code Online (Sandbox Code Playgroud)
那么以当前用户为中心的用户列表将是:
User.objects.all().order_by('-profile__points', 'pk')[index - 5:index + 6]
Run Code Online (Sandbox Code Playgroud)
如果您有很多用户,这种替代方案可能会更慢,因为需要评估当前用户之前的整个用户列表,但我没有验证这一点。
| 归档时间: |
|
| 查看次数: |
840 次 |
| 最近记录: |