]>
git.p6c8.net - pcdenotes.git/blob - 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
.db
.models
.signals
import pre_save
6 from django
.dispatch
import receiver
7 from django
.contrib
.auth
.models
import User
8 from django
.urls
import reverse
10 from datetime
import datetime
12 # Create your models here.
14 NOTE_STATUS
= ((0, "Draft"),
17 class NoteQuerySet(models
.QuerySet
):
20 class NoteManager(models
.Manager
):
21 def per_year(self
, year
):
22 return super().get_queryset().filter(status
=1, created_at__year
=year
)
24 def per_month(self
, year
, month
):
25 return super().get_queryset().filter(status
=1, created_at__year
=year
, created_at__month
=month
)
28 return super().get_queryset().filter(status
=1).annotate(created_year
=ExtractYear('created_at')).values_list('created_year', flat
=True).distinct().order_by('created_year')
30 def years_with_total(self
):
31 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()
33 def months(self
, year
):
34 return self
.per_year(year
).annotate(created_month
=ExtractMonth('created_at')).values_list('created_month', flat
=True).distinct().order_by('created_month')
36 def months_with_total(self
, year
):
37 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()
39 class Note(models
.Model
):
40 title
= models
.CharField(max_length
=250)
41 slug
= models
.SlugField(max_length
=250, unique
=True)
42 author
= models
.ForeignKey(User
, on_delete
=models
.CASCADE
, related_name
='notes_posted')
43 content
= models
.TextField()
44 status
= models
.IntegerField(choices
=NOTE_STATUS
, default
=0)
46 created_at
= models
.DateTimeField(auto_now_add
=True)
47 updated_at
= models
.DateTimeField(auto_now
=True)
48 published_at
= models
.DateTimeField(null
=True, editable
=False)
50 objects
= NoteManager()
53 ordering
= ['-created_at']
58 def get_absolute_url(self
):
59 return reverse("notes:note_detail", kwargs
={"note_slug": self
.slug
})
62 return self
.status
== 0
64 def is_published(self
):
65 return self
.status
== 1
67 @receiver(pre_save
, sender
=Note
)
68 def note_pre_save(sender
, instance
, **kwargs
):
69 if instance
.pk
is None:
70 if instance
.status
== 1:
71 instance
.published_at
= datetime
.now()
73 old_instance
= Note
.objects
.get(pk
=instance
.pk
)
75 if old_instance
.status
== 0 and instance
.status
== 1:
76 instance
.published_at
= datetime
.now()
patrick-canterino.de