python - 复杂的 Django 查询,包括一对一模型

标签 python django

我有一个用户对象,它与个人资料对象具有一对一的关系。

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True, max_length=255)
    mobile = PhoneNumberField(null=True)
    username = models.CharField(null=False, unique=True, max_length=255)
    is_online = models.BooleanField(default=False)


class UserProfile(models.Model):
    user = models.OneToOneField(User,related_name='profile',on_delete=models.CASCADE, )
    badge = models.ImageField(upload_to='media/badges/', null=True)
    reputation = models.IntegerField(default=0)
    status = models.CharField(max_length=255, null=True, blank=True)

现在我试图获取所有在线用户并按信誉(在配置文件对象中)对他们进行排序,并排除信誉低于 200 的用户。

这是我的查询,它不起作用,

User.objects.filter(is_online=True).order_by('reputation').exclude('reputation' < 200)

有人可以帮助解决此查询的正确格式吗?

最佳答案

好吧,如果你写 .exclude('reputation' < 200) ,那么 Python 将首先评估 'reputation' < 200这将 - 在 Python 3.x 中 - 无法比较,而在 Python-2.x 中返回 False ,然后将该 bool 值传递给 exclude .

但请注意,您根本不会过滤声誉。它只是一个 bool 值(最好的情况),您传递给过滤器。

您在 Django 中使用参数名称执行比较:您使用 __lt表示“小于”的后缀。

另一件事是您在 User 上查询, 但声誉存储在 UserProfile 中,你需要遵循反向外键(这个反向关系是针对过滤器 profile ,你可以使用两个连续的下划线再次访问它)。

所以我们可以解决exclude部分:

(User.objects.filter(is_online=True)
                        .order_by('<b>profile__</b>reputation')
                        .exclude(<b>profile__</b>reputation__lt=200))

请注意,如果您排除低于 200 的值,这与过滤等于和大于 200 的值基本相同,因此我们可以将其移至 filter。部分:

(User.objects.filter(is_online=True<b>, profile__reputation__gte=200</b>)
                        .order_by('profile__reputation'))

关于python - 复杂的 Django 查询,包括一对一模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50536266/

相关文章:

python - 字典按月中的天数(键)在 python 中排序

javascript - AngularJS + Django : URL refresh or direct access not loading correctly

python-3.x - Django 休息 : AssertionError: Cannot combine a unique query with a non-unique query

django - 使用 CBV 在 Django 中的一个 View /模板中的两种模型形式

python - 为什么有些 numpy 调用没有作为方法实现?

python - 值错误: seek of closed file Working on PyPDF2 and getting this error

python - 为 Pandas 使用多个核心

python - 从两个给定的 pd.Series 创建 pandas 系列

django - 如何在 django 中设置 choicefield 的值

python - 成功注销后重定向django内置注销 View