]>
git.p6c8.net - pcdenotes.git/blob - notes/models.py
c38e3d50ae85d41986298f39ad5331c5744c09b7
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 all_published(self
):
22 return super().get_queryset().filter(status
=1)
24 def all_with_unpublished(self
):
27 def per_year(self
, year
):
28 return self
.all_published().filter(created_at__year
=year
)
30 def per_month(self
, year
, month
):
31 return self
.per_year(year
).filter(created_at__month
=month
)
34 return self
.all_published().annotate(created_year
=ExtractYear('created_at')).values_list('created_year', flat
=True).distinct().order_by('created_year')
36 def years_with_total(self
):
37 return self
.all_published().annotate(created_year
=ExtractYear('created_at')).values('created_year').annotate(total
=Count('id')).order_by('created_year').values('created_year', 'total').distinct()
39 def months(self
, year
):
40 return self
.per_year(year
).annotate(created_month
=ExtractMonth('created_at')).values_list('created_month', flat
=True).distinct().order_by('created_month')
42 def months_with_total(self
, year
):
43 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()
45 class Note(models
.Model
):
46 title
= models
.CharField(max_length
=250)
47 slug
= models
.SlugField(max_length
=250, unique
=True)
48 author
= models
.ForeignKey(User
, on_delete
=models
.CASCADE
, related_name
='notes_posted')
49 content
= models
.TextField()
50 status
= models
.IntegerField(choices
=NOTE_STATUS
, default
=0)
52 created_at
= models
.DateTimeField(auto_now_add
=True)
53 updated_at
= models
.DateTimeField(auto_now
=True)
54 published_at
= models
.DateTimeField(null
=True, editable
=False)
56 objects
= NoteManager()
59 ordering
= ['-created_at']
64 def get_absolute_url(self
):
65 return reverse("notes:note_detail", kwargs
={"note_slug": self
.slug
})
68 return self
.status
== 0
70 def is_published(self
):
71 return self
.status
== 1
73 def publication_date(self
):
74 if self
.published_at
is None:
75 return self
.created_at
77 return self
.published_at
79 @receiver(pre_save
, sender
=Note
)
80 def note_pre_save(sender
, instance
, **kwargs
):
81 if instance
.pk
is None:
82 if instance
.status
== 1:
83 instance
.published_at
= datetime
.now()
85 old_instance
= Note
.objects
.get(pk
=instance
.pk
)
87 if old_instance
.status
== 0 and instance
.status
== 1:
88 instance
.published_at
= datetime
.now()
patrick-canterino.de