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

patrick-canterino.de