You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django一对一模型关联查询:在线用户按声望排序并过滤

Django查询:获取在线且声望达标用户并排序

我来帮你修正这个查询语句,先看看你原来代码里的两个关键问题:

  • reputation是UserProfile的字段,不是User本身的字段,直接写reputation会导致字段不存在的错误,得通过一对一关联的profile(你设置的related_name)来跨表查询,格式是profile__reputation
  • exclude('reputation' < 200)的语法完全不对,Django的查询方法需要用字段查询的格式,不能直接写Python的比较表达式

下面是两种正确的写法,推荐第一种更直观的:

推荐写法(直接筛选符合条件的用户)

# 获取在线、声望≥200的用户,按声望升序排序
User.objects.filter(
    is_online=True,
    profile__reputation__gte=200
).order_by('profile__reputation')

如果想要按声望降序排序,只需要在字段前加负号:

.order_by('-profile__reputation')

使用exclude的写法

如果你坚持想用exclude来排除声望低于200的用户,语法应该是这样的:

User.objects.filter(is_online=True).exclude(
    profile__reputation__lt=200
).order_by('profile__reputation')

补充说明

如果你的项目中存在User没有对应UserProfile的情况(虽然一对一关联理论上应该一一对应,但如果有特殊场景),可以在filter里加上profile__isnull=False来避免报错:

User.objects.filter(
    is_online=True,
    profile__isnull=False,
    profile__reputation__gte=200
).order_by('profile__reputation')

内容的提问来源于stack exchange,提问作者Melissa Stewart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:49:51