在Django中,获取各种条件的多个计数

2024-06-02 14:43:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Django 2.2开发“管理仪表板”

我将从一个表中计算各种条件的“对象”,并将它们发送到模板

我的代码在下面

# model
class User(models.Model):
    uid = models.AutoField(primary_key=True)
    status = models.IntegerField(blank=True, null=True)
    created_at = models.DateTimeField(blank=True, null=True)
    created_at_unix = models.CharField(max_length=100, blank=True, null=True)
    country_code = models.IntegerField(blank=True, null=True)
    recommender_id = models.ForeignKey('self', on_delete=models.SET_NULL ,blank=True, null=True, db_column='recommender_id')
    is_agreement = models.PositiveIntegerField(blank=True, null=True)
    delete_yn = models.CharField(max_length=1, default='n')
    is_sms = models.PositiveIntegerField(blank=True, null=True)
    is_email = models.PositiveIntegerField(blank=True, null=True)
    is_push = models.PositiveIntegerField(blank=True, null=True)



def index(request):
    # New User
    user_lastweek = User.objects.filter(created_at__gte=last_monday, created_at__lte=last_sunday).count()
    user_thisweek = User.objects.filter(created_at__gte=this_monday, created_at__lte=tomorrow).count()
    user_variation = user_thisweek - user_lastweek
    # User total
    user_total_lastweek = User.objects.filter(created_at__lte=last_sunday).count()
    user_total_thisweek = User.objects.filter(created_at__lte=tomorrow).count()
    user_total_variation = user_total_thisweek - user_total_lastweek

    context = {
    'user_lastweek':user_lastweek,
    ...

    }
    return render(request, 'main/index.html', context)

我只写了许多条件中的几个

但是我的代码每次都会导致重复的查询命中

我需要的结果是

1. user_lastweek : 114
2. user_thisweek : 98
3. user_total_lastweek : 1232
4. user_total_thisweek : 1330

仅使用一个查询或更少的查询渲染到模板的效率如何


Tags: trueobjectsismodelsfilternullattotal
1条回答
网友
1楼 · 发布于 2024-06-02 14:43:20

我自己解决的

我应该多读些关于Django的文档

使用.aggregate()

test = User.objects.aggregate(
        last = Count('pk', filter=Q(created_at__lte=last_sunday)),
        this = Count('pk', filter=Q(created_at__lte=tomorrow)),
        last1 = Count('pk', filter=Q(created_at__gte=last_monday, created_at__lte=last_sunday)),
        this1=Count('pk', filter=Q(created_at__gte=this_monday, created_at__lte=tomorrow)),
    )
    print(test)
{'last': 1011, 'this': 1018, 'last1': 38, 'this1': 1}

相关问题 更多 >