Janik Spies
Janik Spies

Reputation: 427

Django Get Entries Separated by Month

I've got an object called entry. This object has a CharField, a DateField and a ForeignKey to a status. (The status could be "Error" or "Warning")
I now want to do a page where the user can see how many entries with the status "Error" and "Warning" got created a certain number of months until today. I already got the logic that the url has a kwarg that shows the number of months. Here is what I have so far in my views.py:

class graph_view(View, LoginRequiredMixin):
    def get(self, request, **kwargs):
        timeline = get_object_or_404(Timeline, id=kwargs.get('pk'))
        months = kwargs.get('months')


The Result should look something like this:

August: 5 Errors, 2 Warnings
September: 4 Errors, 6 Warnings
October: 0 Errors, 5 Warnings
November: 2 Errors, 4 Warnings

In the excample above the user selected that he wants to see the entries over the last 4 months.

Does anyone have an idea how i can query these entries?

Thanks for any help.

Upvotes: 0

Views: 154

Answers (1)

shourav
shourav

Reputation: 996

You can get errors and warning separately like this.

from django.db.models.functions import TruncMonth
from django.db.models import Count


Entry.objects.filter(status='Error').annotate(month=TruncMonth('created')).values('month').annotate(c=Count('pk')).values('month', 'c') 

where created is DateField and status is the ForeignKey. Here we are grouping by the months

Upvotes: 3

Related Questions