gpt4 book ai didi

django 过滤器两个 ManyToManyField 相等

转载 作者:行者123 更新时间:2023-12-04 07:56:06 30 4
gpt4 key购买 nike

class VideoUserModel(models.Model):
user = models.ManyToManyField(get_user_model())
viewlist = models.ManyToManyField(get_user_model(), related_name='view_list', blank=True, null=True)
我想获取 user 的查询集列表等于 viewlist .
这该怎么做? VideoUserModel.objects.all().filter(user=**viewlist**)

最佳答案

对此没有简单的答案。我们可以通过计算 nuser 的数量来做到这一点。 s,viewlist中的项目数关系和 user 中的项目数也在 nuser然后检查这三个是否都相等:

from django.db.models import Count, F, Q

VideoUserModel.objects.annotate(
nuser=Count('user', distinct=True),
nview=Count('viewlist', distinct=True),
nuserfilter=Count('user', filter=Q(user=F('viewlist')), distinct=True)
).filter(
nuser=F('nview'),
nview=F('nuserfilter')
)

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to work with the get_user_model() method [Django-doc], since that requires loading the auth app before the current app. For more information you can see the referencing the User model section of the documentation.

关于django 过滤器两个 ManyToManyField 相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66694907/

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