-
Notifications
You must be signed in to change notification settings - Fork 10
/
models.py
45 lines (32 loc) · 1.2 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from django.core.exceptions import FieldDoesNotExist
from django.db import models
from .managers import BaseManager
class ValidateModelMixin(object):
def save(self, *args, **kwargs):
"""
Call `full_clean` before saving.
"""
self.full_clean()
return super().save(*args, **kwargs)
class BaseModel(ValidateModelMixin, models.Model):
objects = BaseManager()
def save(self, *args, **kwargs):
self.generate_id_if_needed()
kwargs["update_fields"] = None
return super().save(*args, **kwargs)
def generate_id_if_needed(self):
try:
field = self._meta.get_field('id')
if ((not (self.id)) and (hasattr(field, 'generate_id'))):
self.id = field.generate_id()
while (self._meta.model.objects.filter(id=self.id).exists()):
self.id = field.generate_id()
except FieldDoesNotExist:
pass
class Meta:
abstract = True
class TimeStampedModel(BaseModel):
date_created = models.DateTimeField(auto_now_add=True, db_index=True)
date_updated = models.DateTimeField(auto_now=True, db_index=True)
class Meta:
abstract = True