1 """ This module contains abstract models that are used in multiple apps """
3 from __future__
import absolute_import
, unicode_literals
7 from uuidfield
import UUIDField
9 from django
.db
import models
, connection
12 logger
= logging
.getLogger(__name__
)
15 class UUIDModel(models
.Model
):
16 """ Models that have an UUID as primary key """
18 id = UUIDField(primary_key
=True)
24 """ String representation of the ID """
28 class TwitterModel(models
.Model
):
29 """ A model that has a twitter handle """
31 twitter
= models
.CharField(max_length
=15, null
=True, blank
=False)
37 class SettingsModel(models
.Model
):
38 """ A model that can store arbitrary settings as JSON """
40 settings
= models
.TextField(null
=False, default
='{}')
45 def get_wksetting(self
, setting
):
46 """ returns the value of a well-known setting """
48 settings
= json
.loads(self
.settings
)
49 except ValueError as ex
:
50 logger
.warn('Decoding settings failed: {msg}'.format(msg
=str(ex
)))
53 return settings
.get(setting
.name
, setting
.default
)
55 def set_wksetting(self
, setting
, value
):
57 settings
= json
.loads(self
.settings
)
58 except ValueError as ex
:
59 logger
.warn('Decoding settings failed: {msg}'.format(msg
=str(ex
)))
61 settings
[setting
.name
] = value
62 self
.settings
= json
.dumps(settings
)
64 def get_setting(self
, name
, default
):
65 settings
= json
.loads(self
.settings
)
66 return settings
.get(name
, default
)
68 def set_setting(self
, name
, value
):
69 settings
= json
.loads(self
.settings
)
70 settings
[name
] = value
71 self
.settings
= json
.dumps(settings
)
74 class GenericManager(models
.Manager
):
75 """ Generic manager methods """
78 """ Fast approximate count of all model instances
80 PostgreSQL is slow when counting records without an index. This is a
81 workaround which only gives approximate results. see:
82 http://wiki.postgresql.org/wiki/Slow_Counting """
83 cursor
= connection
.cursor()
84 cursor
.execute("select reltuples from pg_class where relname='%s';" %
85 self
.model
._meta
.db_table
)
86 row
= cursor
.fetchone()
90 class UpdateInfoModel(models
.Model
):
91 """ Model that keeps track of when it was created and updated """
92 created
= models
.DateTimeField(auto_now_add
=True)
93 modified
= models
.DateTimeField(auto_now
=True)
99 class DeleteableModel(models
.Model
):
100 """ A model that can be marked as deleted """
102 # indicates that the object has been deleted
103 deleted
= models
.BooleanField(default
=False)
109 class OrderedModel(models
.Model
):
110 """ A model that can be ordered
112 The implementing Model must make sure that 'order' is sufficiently unique
115 order
= models
.PositiveSmallIntegerField()