change separators for easier escaping
[wolnelektury.git] / src / api / models.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from django.contrib.auth.models import User
6 from django.contrib.contenttypes.models import ContentType
7 from django.db import models
8 from django.db.models.signals import pre_delete
9 from django.utils.translation import ugettext_lazy as _
10
11 from catalogue.models import Book, Tag
12
13
14 class Deleted(models.Model):
15     object_id = models.IntegerField()
16     slug = models.SlugField(_('slug'), max_length=120, blank=True, db_index=True)
17     content_type = models.ForeignKey(ContentType)
18     category = models.CharField(max_length=64, null=True, blank=True, db_index=True)
19     created_at = models.DateTimeField(editable=False, db_index=True)
20     deleted_at = models.DateTimeField(auto_now_add=True, db_index=True)
21
22     class Meta:
23         unique_together = (('content_type', 'object_id'),)
24
25
26 def _pre_delete_handler(sender, instance, **kwargs):
27     """ save deleted objects for change history purposes """
28
29     if sender in (Book, Tag):
30         if sender == Tag:
31             if instance.category in ('book', 'set'):
32                 return
33             else:
34                 category = instance.category
35         else:
36             category = None
37         content_type = ContentType.objects.get_for_model(sender)
38         Deleted.objects.create(
39             content_type=content_type, object_id=instance.id, created_at=instance.created_at, category=category,
40             slug=instance.slug)
41 pre_delete.connect(_pre_delete_handler)
42
43
44 class BookUserData(models.Model):
45     book = models.ForeignKey(Book)
46     user = models.ForeignKey(User)
47     complete = models.BooleanField(default=False)
48
49     def get_state(self):
50         return 'complete' if self.complete else 'reading'
51
52     def set_state(self, state):
53         self.complete = state == 'complete'
54
55     state = property(get_state, set_state)