Generateurv2/backend/api/exercices/models.py
2022-06-24 13:42:16 +02:00

81 lines
2.2 KiB
Python

from django.db import models
import random
import string
from django.db.models.fields import CharField, IntegerField, TextField, BooleanField, DateTimeField
from django.db.models.fields.json import JSONField
from users.models import CustomUser
# Create your models here.
def generate_unique_code_step():
length = 6
while True:
code = ''.join(random.choices(string.ascii_uppercase, k=length))
if Exercice.objects.filter(id_code=code).count() == 0:
break
return code
def generate_unique_code_tag():
length = 6
while True:
code = ''.join(random.choices(string.ascii_uppercase, k=length))
if Tag.objects.filter(id_code=code).count() == 0:
break
return code
class Tag(models.Model):
color = CharField(max_length=50, default='')
id_code = CharField(max_length=50, unique=True,
default=generate_unique_code_tag)
user = models.ForeignKey('users.CustomUser', null=True, on_delete=models.CASCADE)
name = CharField(max_length=25, default='')
def exo_code(instance, filename):
return f'uploads/exercices/exo_{instance.id_code}/{filename}'
class ExerciceManager(models.Manager):
def delete(self):
for obj in self.get_queryset():
obj.delete()
class Exercice(models.Model):
name = CharField(max_length=50)
id_code = CharField(
unique=True, max_length=50, default=generate_unique_code_step)
exo_model = models.FileField(upload_to=exo_code)
consigne = CharField(max_length=100, default='', blank=True)
tags = models.ManyToManyField(Tag)
exemple = JSONField(default=dict)
isPdf = BooleanField(default=True)
isCsv = BooleanField(default=True)
isWeb = BooleanField(default=True)
last_update = DateTimeField(auto_now_add=True)
original = BooleanField(default=True)
origin = models.ForeignKey('self', null=True, on_delete = models.SET_NULL)
private = BooleanField(default=False)
author = models.ForeignKey(CustomUser, null=True, on_delete=models.CASCADE)
objects = ExerciceManager()
def delete(self, using=None, keep_parents=False):
self.exo_model.storage.delete(self.exo_model.name)
super().delete()