expqr/core/models.py

113 lines
No EOL
3.2 KiB
Python

from django.db.models import Model, UUIDField, CharField, TextField, ForeignKey, CASCADE, PositiveIntegerField, SET_NULL
import uuid
import string
import random
class Series(Model):
id = CharField(primary_key=True, max_length=10)
uuid = UUIDField(unique=True)
title = CharField(max_length=128, blank=True, null=True)
description = TextField(blank=True, null=True)
@classmethod
def generate_id(cls):
id = "".join(random.SystemRandom().choices(string.digits + string.ascii_letters, k=10))
try:
cls.objects.get(id=id)
except cls.DoesNotExist:
return id
return cls.generate_id()
@classmethod
def generate_uuid(cls):
id = uuid.uuid4()
try:
cls.objects.get(uuid=id)
except cls.DoesNotExist:
return id
return cls.generate_uuid()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not self.id:
self.id = self.generate_id()
if not self.uuid:
self.uuid = self.generate_uuid()
class Code(Model):
id = CharField(max_length=5)
uuid = UUIDField(primary_key=True)
title = CharField(max_length=128)
series = ForeignKey(Series, CASCADE)
order = PositiveIntegerField()
class Meta:
unique_together = [["id", "series"]]
@classmethod
def generate_id(cls):
id = "".join(random.SystemRandom().choices(string.digits + string.ascii_letters, k=5))
try:
cls.objects.get(id=id)
except cls.DoesNotExist:
return id
return cls.generate_id()
@classmethod
def generate_uuid(cls):
id = uuid.uuid4()
try:
cls.objects.get(uuid=id)
except cls.DoesNotExist:
return id
return cls.generate_uuid()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not self.id:
self.id = self.generate_id()
if not self.uuid:
self.uuid = self.generate_uuid()
if not self.order:
self.order = max([code.order for code in self.series.code_set.all()] + [0]) + 1
class Content(Model):
literal = TextField()
code = ForeignKey(Code, SET_NULL, null=True)
class Media(Model):
uuid = UUIDField(primary_key=True)
content = ForeignKey(Content, CASCADE)
@classmethod
def generate_uuid(cls):
id = uuid.uuid4()
try:
cls.objects.get(uuid=id)
except cls.DoesNotExist:
return id
return cls.generate_uuid()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not self.uuid:
self.uuid = self.generate_uuid()
class APIKey(Model):
key = UUIDField(primary_key=True)
description = CharField(max_length=256, blank=True, null=True)
@classmethod
def generate_uuid(cls):
id = uuid.uuid4()
try:
cls.objects.get(key=id)
except cls.DoesNotExist:
return id
return cls.generate_uuid()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not self.key:
self.key = self.generate_uuid()