python - 根据相关字段的计数排除
问题描述
我有经典的标题和条目模型,其中标题是条目模型中的外键。我使用 users 模型的默认first_name
字段来暂停用户,因此如果用户被暂停,则该first_name
字段设置为blocked
. 我还有一个模型可以让用户互相阻止:
class Block(models.Model):
blocker= models.ForeignKey("auth.user",on_delete=
models.CASCADE,related_name="blocker")
blocked= models.ForeignKey("auth.user",on_delete=
models.CASCADE,related_name="blocked")
如果在排除被阻止和暂停的用户后没有属于标题的条目,我想要做的是在排除标题的同时显示标题。换句话说,如果相关条目计数在排除后> 0,则过滤标题。我一直在使用下面的代码来解决这个问题:
title= Popular.objects.all().order_by("-rating")
titles= []
followed_count= None
paginator = Paginator(title, 1)
page = request.GET.get('page', 1)
try:
entries2 = paginator.page(page)
except PageNotAnInteger:
entries2 = paginator.page(1)
except EmptyPage:
entries2 = paginator.page(paginator.num_pages)
page_list = entries2.paginator.page_range
for title in entries2:
if request.user.is_authenticated:
followed_count= Entry.objects.filter(user__followed__follower=request.user,title=title.title,created_date__gte=date_from).exclude(user__last_name="blocked").count()
blocked_count= Entry.objects.filter(user__blocked__blocker=request.user,title=title.title,created_date__gte=date_from).exclude(user__last_name="blocked").count()
else:
blocked_count= 0
suspend_count= Entry.objects.filter(user__last_name="blocked",title=title.title,created_date__gte=date_from,).count()
amount= Entry.objects.filter(title=title.title,created_date__gte=date_from).count()
amount -= blocked_count + suspend_count
if amount == 0:
continue
titles.append({"title":title.title,"url":title.title.title_url,"rating":title.rating,"title_id":title.title_id,"amount":amount,"followed_count":followed_count}
但是如果有没有条目的标题会导致分页器创建空页面,我也不想将分页代码放在最后,因为我不想遍历整个数据库。
解决方案
推荐阅读
- javascript - 如何在html的输入字段中突出显示新文本
- c - 试图在 C 中捕获 SIGSEGV 信号
- python - 我正在尝试使用 for 循环创建 3D 矩阵
- r - 如何在 R 中取消嵌套数据框列表的列表?
- c - 如何在两个不同的程序之间分离两个scanfs?
- c++ - C++ 中字符串的 32 位 LFSR 加密
- node.js - 如何使用 axios (Vue.js) 将我的参数 req.body 填充到我的 Express.js 服务器
- amazon-web-services - 如何通过 Terraform 描述 API Gateway 资源?
- azure-service-fabric - 服务结构复制器卡住
- numerical-methods - 如何以数值稳定的方式计算 (exp(t) - 1)/t?