gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:30:31 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com