构建Django中每日新用户数的列表

时间:2012-02-29 06:33:08

标签: django django-queryset

我想建立一个每日用户注册计数列表。以下是我这样做的方式,但这是最合乎逻辑的方式吗?

users = User.objects.all()
oldest_user_date = users.order_by('date_joined')[0].date_joined
day_difference = (datetime.now() - oldest_user_date).days

historical_user_signups_per_day = []
while day_difference > 0:
    days_user_signups = users.filter(date_joined__gt=datetime.now()-timedelta(days=day_difference+1), date_joined__lt=datetime.now()-timedelta(days=day_difference)).count()
    daily_count = {
        'count': days_user_signups,
        'date': datetime.now()-timedelta(days=day_difference)
    }
    historical_user_signups_per_day.append(daily_count)
    day_difference -= 1

3 个答案:

答案 0 :(得分:1)

一天:

daily_users = User.objects.filter(date_joined__day=datetime.today().day).count()

在一段时间内:

users = User.objects.all()
count_by_day = [{'count':users.filter(date_joined__day=x.day).count(), \
                 'date':x} \ 
                  for x in User.objects.dates('date_joined','days')]

答案 1 :(得分:0)

查找当天的新用户数:

def get_curr_day_new_user_count():
     from datetime import date
     from django.contrib.auth.models import User

     today = date.today()
     return User.objects.filter(date_joined__contains=today).count()

答案 2 :(得分:0)

当我遇到相同的问题时,我在Django文档中进行了研究,发现date_joined的格式为"YYYY-MM-DD HH:MM:SS"。由于您希望所有用户在一天内而不是一秒钟之内,您可以查看date_joined是否包含datetime库中的,我在下面将其称为reference_date

oldest_user_date = User.objects.order_by('date_joined')[0].date_joined
day_difference = (datetime.now() - oldest_user_date).days
historical_user_signups_per_day = []

for i in range(day_difference):
    reference_date = datetime.now() - timedelta(days=i)
    historical_user_signups_per_day.append({
        'count': Users.objects.filter(date_joined__contains=reference_date).count(),
        'date': reference_date
    })
  

此代码可在当前最新版本的Django 3.0中使用