views:

39

answers:

1

With a model like this:

class User(models.Model):
    entered = models.DateTimeField(auto_now_add=True)

How to grab stats data so it show recent added users for last 30 days with number of users added on that day.

Example:

2010-08-02: 220
2010-08-08: 1220
2010-08-14: 20
+3  A: 

Update:

This answer is not useful. As entered is a DateTimeField the query will end up with a count of 1 for each value of entered. This is not what the OP wanted. (Thanks dannyroa)

Changing the type of entered to DateField should help.

Original Answer

You can use Django's aggregation feature to do this. Something like this:

from django.db.models import Count
q = User.objects.annotate(Count('entered')).order_by('-entered')
for user in q[0:30]:
    print "%s %s" % (user.entered, user.entered__count)

Update

You can slice the queryset and then pass it into the template.

# View 
def my_view(*args, **kwargs):
    queryset = User.objects.annotate(Count('entered')).order_by('-entered')
    context = dict(queryset = queryset[0:30])
    return render_to_response('my_template.html', context_instance = RequestContext(request, context))    

# Template
{% for user in queryset %}
    <td>{{ user.entered }}</td>
    <td>{{ user.entered_count }}</td>
{% endfor %}
Manoj Govindan
thanks, silly question, how to carry over q[0:30] data to templates
bobsr
@bobsr: Have updated my answer. See above.
Manoj Govindan
Pass your context as a dictionary argument not with RequestContext:`return render_to_response('my_template.html', context, context_instance = RequestContext(request))`
rebus
I haven't tested the code but wouldn't the result be like this?2010-08-02 06:00:01 : 12010-08-02 06:10:10 : 12010-08-01 12:00:01 : 12010-08-01 12:10:10 : 1It will be grouped by datetime not just by date so the count will always be one.
dannyroa