[Answer]-Django get count based on foreign Key for every month

1👍

Just make a query with time range:

import datetime
from models import click_info

def get_click_by_month(month, year, hash):
    d1 = datetime.datetime(year=year, month=month, day=1)
    d2 = datetime.datetime(year=year, month=month + 1, day=1)
    clicks = click_info.objects.filter(url_hash=hash, created_at__range=[d1, d2])
    return len(clicks)

P.S. PEP8 recommends to use CamelCase to name classes. Of course it’s not obligatory but at least people inside the team must use same principles of code writing. Using PEP8 is just easier than creating your own rules.

👤WebPal

Leave a comment