首页 > 解决方案 > 根据相关字段的计数排除

问题描述

我有经典的标题和条目模型,其中标题是条目模型中的外键。我使用 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}

但是如果有没有条目的标题会导致分页器创建空页面,我也不想将分页代码放在最后,因为我不想遍历整个数据库。

标签: pythonmysqldjangodatabaseorm

解决方案


推荐阅读