my_book_list_api/books/models.py
2025-12-06 21:54:47 +01:00

67 lines
1.8 KiB
Python

import os
from uuid import uuid4
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from django.core.validators import MaxValueValidator
def upload_avatar(instance, filename):
ext = filename.split('.')[-1]
filename = '{}.{}'.format(uuid4().hex, ext)
return os.path.join('avatars/', filename)
def upload_illustration(instance, filename):
ext = filename.split('.')[-1]
filename = '{}.{}'.format(uuid4().hex, ext)
return os.path.join('illustrations/', filename)
class Book(models.Model):
PLAN_TO_READ = 'PLAN'
READING = 'READING'
COMPLETED = 'COMPLETED'
DROPPED = 'DROPPED'
STATE_CHOICES = [
(PLAN_TO_READ, _('Plan to Read')),
(READING, _('Reading')),
(COMPLETED, _('Completed')),
(DROPPED, _('Dropped')),
]
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='books'
)
note = models.PositiveSmallIntegerField(
_('note'),
validators=[MaxValueValidator(10)],
default=0,
null=True,
blank=True
)
title = models.CharField(max_length=255)
author = models.CharField(max_length=255)
illustration = models.ImageField(upload_to=upload_illustration)
state = models.CharField(
_('state'),
max_length=10,
choices=STATE_CHOICES,
default=PLAN_TO_READ,
db_index=True
)
added_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return f"{self.title} ({self.user.username})"
class CustomUser(AbstractUser):
avatar = models.ImageField(upload_to=upload_avatar)
def __str__(self):
return self.username