]> git.p6c8.net - pcdenotes.git/blob - notes/models.py
Display number of notes in archive view
[pcdenotes.git] / notes / models.py
1 from django.db import models
2 from django.db.models import Count
3 from django.db.models.functions import ExtractYear, ExtractMonth
4 from django.contrib.auth.models import User
5 from django.urls import reverse
6
7 # Create your models here.
8
9 NOTE_STATUS = ((0, "Draft"),
10 (1, "Published"))
11
12 class NoteQuerySet(models.QuerySet):
13 pass
14
15 class NoteManager(models.Manager):
16 def per_year(self, year):
17 return super().get_queryset().filter(status=1, created_at__year=year)
18
19 def per_month(self, year, month):
20 return super().get_queryset().filter(status=1, created_at__year=year, created_at__month=month)
21
22 def years(self):
23 return super().get_queryset().filter(status=1).annotate(created_year=ExtractYear('created_at')).values_list('created_year', flat=True).distinct().order_by('created_year')
24
25 def years_with_total(self):
26 return super().get_queryset().filter(status=1).annotate(created_year=ExtractYear('created_at')).values('created_year').annotate(total=Count('id')).order_by('created_year').values('created_year', 'total').distinct()
27
28 def months(self, year):
29 return self.per_year(year).annotate(created_month=ExtractMonth('created_at')).values_list('created_month', flat=True).distinct().order_by('created_month')
30
31 def months_with_total(self, year):
32 return self.per_year(year).annotate(created_month=ExtractMonth('created_at')).values('created_month').annotate(total=Count('id')).order_by('created_month').values('created_month', 'total').distinct()
33
34 class Note(models.Model):
35 title = models.CharField(max_length=250)
36 slug = models.SlugField(max_length=250, unique=True)
37 author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='notes_posted')
38 content = models.TextField()
39 status = models.IntegerField(choices=NOTE_STATUS, default=0)
40
41 created_at = models.DateTimeField(auto_now_add=True)
42 updated_at = models.DateTimeField(auto_now=True)
43
44 objects = NoteManager()
45
46 class Meta:
47 ordering = ['-created_at']
48
49 def __str__(self):
50 return self.title
51
52 def get_absolute_url(self):
53 return reverse("notes:note_detail", kwargs={"note_slug": self.slug})
54
55 def is_draft(self):
56 return self.status == 0
57
58 def is_published(self):
59 return self.status == 1

patrick-canterino.de