Django问与答在同一个领域? [英] Django Q Queries & on the same field?

查看:96
本文介绍了Django问与答在同一个领域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的模特:

class Event(models.Model):
    user = models.ForeignKey(User, blank=True, null=True, db_index=True)
    name = models.CharField(max_length = 200, db_index=True)
    platform = models.CharField(choices = (("ios", "ios"), ("android", "android")), max_length=50)

class User(AbstractUser):
    email = models.CharField(max_length=50, null=False, blank=False, unique=True)

Event就像一个分析事件,因此,如果一个用户登录了多个设备,则很有可能一个用户有多个事件,某些事件使用platform=ios,有些事件使用platform=android.我想查询一下有多少用户同时拥有ios和android设备.所以我写了这样的查询:

Event is like an analytics event, so it's very possible that I could have multiple events for one user, some with platform=ios and some with platform=android, if a user has logged in on multiple devices. I want to query to see how many users have both ios and android devices. So I wrote a query like this:

User.objects.filter(Q(event__platform="ios") & Q(event__platform="android")).count()

哪个返回0个结果.我知道这是不正确的.然后我以为我会尝试只查询iOS用户:

Which returns 0 results. I know this isn't correct. I then thought I would try to just query for iOS users:

User.objects.filter(Q(event__platform="ios")).count()

哪个返回了6,717,622个结果,这是意外的,因为我只有39,294个用户.我猜它不是在计算用户,而是在计算Event实例,这对我来说似乎是错误的行为.有人对这个问题有见识吗?

Which returned 6,717,622 results, which is unexpected because I only have 39,294 users. I'm guessing it's not counting the Users, but counting the Event instances, which seems like incorrect behavior to me. Does anyone have any insights into this problem?

推荐答案

您可以改用注释:

django.db.models import Count

User.objects.all().annotate(events_count=Count('event')).filter(events_count=2)

因此它将过滤掉具有两个事件的所有用户.

So it will filter out any user that has two events.

您还可以使用链接过滤器:

You can also use chained filters:

User.objects.filter(event__platform='android').filter(event__platform='ios')

第一个过滤器将获取所有具有android平台的用户,第二个过滤器将获取也具有iOS平台的用户.

Which first filter will get all users with android platform and the second one will get the users that also have iOS platform.

这篇关于Django问与答在同一个领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆