chrono/chrono/agendas/models.py

76 lines
2.5 KiB
Python

# chrono - agendas system
# Copyright (C) 2016 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models.expressions import RawSQL
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONField
class Agenda(models.Model):
label = models.CharField(_('Label'), max_length=50)
slug = models.SlugField(_('Slug'))
class Meta:
ordering = ['label']
def save(self, *args, **kwargs):
if not self.slug:
base_slug = slugify(self.label)
slug = base_slug
i = 1
while True:
try:
Agenda.objects.get(slug=slug)
except self.DoesNotExist:
break
slug = '%s-%s' % (base_slug, i)
i += 1
self.slug = slug
super(Agenda, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('chrono-manager-agenda-view', kwargs={'pk': self.id})
class EventManager(models.Manager):
def get_queryset(self):
return super(EventManager, self).get_queryset().annotate(
booked_places=RawSQL('''SELECT count(*)
FROM agendas_booking
WHERE agendas_booking.event_id = agendas_event.id
AND cancellation_datetime IS NULL''', ()))
class Event(models.Model):
agenda = models.ForeignKey(Agenda)
start_datetime = models.DateTimeField(_('Date/time'))
places = models.PositiveIntegerField(_('Places'))
objects = EventManager()
class Meta:
ordering = ['agenda', 'start_datetime']
class Booking(models.Model):
event = models.ForeignKey(Event)
extra_data = JSONField(null=True)
cancellation_datetime = models.DateTimeField(null=True)