Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from datetime import datetime
- from django.contrib.auth.base_user import AbstractBaseUser
- from django.contrib.auth.models import PermissionsMixin, UserManager
- from django.db import models
- class CustomUser(AbstractBaseUser, PermissionsMixin):
- """Расширенный пользователь"""
- username = models.CharField('Пользователь', max_length=25, unique=True)
- email = models.EmailField('Email', unique=True)
- date_joined = models.DateTimeField('Дата регистрации', auto_now_add=True)
- is_active = models.BooleanField('is_active', default=True)
- is_staff = models.BooleanField('is_staff', default=False)
- user_photo = models.ImageField(upload_to='media/users_photos/', null=True, blank=True)
- objects = UserManager()
- USERNAME_FIELD = 'username'
- REQUIRED_FIELDS = []
- class Meta:
- db_table = 'user'
- verbose_name = 'Пользователь'
- verbose_name_plural = 'Пользователи'
- class Product(models.Model):
- """Продукт"""
- class Colors(models.TextChoices):
- RED = 'RED', 'Красный'
- TOMATO = 'TOMATO', 'Томатный'
- GREEN = 'GREEN', 'Зеленый'
- AQUA = 'AQUA', 'Аква'
- VIOLET = 'VIOLET', 'Фиолетовый'
- WHITE = 'WHITE', 'Белый'
- BLACK = 'BLACK', 'Нигерский'
- DEFAULT = 'DEFAULT', 'По умолчанию'
- name = models.CharField('Название', max_length=150)
- description = models.TextField('Описание', max_length=500)
- preview = models.ImageField(upload_to='media/products/', null=True, blank=True)
- price = models.PositiveSmallIntegerField('Цена', default=0)
- color = models.CharField('Цвета', choices=Colors.choices, default=Colors.DEFAULT)
- characteristics = models.ForeignKey(
- 'Characteristic', on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Характеристики'
- )
- url = models.SlugField('Ссылка', max_length=250, unique=True)
- def __str__(self):
- return self.name
- #Добавить метод get_abs_url см в гугле
- class Meta:
- db_table = 'product'
- verbose_name = 'Продукт'
- verbose_name_plural = 'Продукты'
- class ProductImages(models.Model):
- """Изображения продукта"""
- image = models.ImageField(upload_to='media/products/') # Тут будут храниться все фото , отфильтруй по папкам
- # Можно добавить name или description для фото
- product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='Продукт')
- class Meta:
- db_table = 'product_images'
- verbose_name = 'Изображение'
- verbose_name_plural = 'Изображения'
- class ProductReview(models.Model):
- """Отзывы к продукту"""
- customer = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, verbose_name='Покупатель')
- product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='Продукт')
- text = models.TextField('Отзыв', max_length=250)
- # Я бы сделал тут не Fk а ContentType, Но не критично
- parent = models.ForeignKey(
- 'self', on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Родительский отзыв'
- )
- def __str__(self):
- return f'{self.customer} - {self.text}'
- class Meta:
- db_table = 'product_review'
- verbose_name = 'Отзыв к продукту'
- verbose_name_plural = 'Отзывы к продукту'
- class RatingStar(models.Model):
- """Звезда рейтинга"""
- value = models.PositiveSmallIntegerField('Значение', default=0)
- def __str__(self):
- return self.value
- class Meta:
- db_table = 'rating_star'
- verbose_name = 'Звезда рейтинга'
- verbose_name_plural = 'Звёзды рейтинга'
- class Rating(models.Model):
- """Рейтинг"""
- customer = models.ForeignKey(
- CustomUser, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Покупатель'
- )
- star = models.ForeignKey(RatingStar, on_delete=models.CASCADE, verbose_name='Звезда')
- product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='Продукт')
- def __str__(self):
- return f'{self.customer} - {self.star}'
- class Meta:
- db_table = 'rating'
- verbose_name = 'Рейтинг'
- verbose_name_plural = 'Рейтинг'
- class Characteristic(models.Model):
- """Характеристики"""
- class CompositionType(models.TextChoices):
- STEEL = 'STEEL', 'Сталь'
- IRON = 'IRON', 'Железо'
- ALUMINIUM = 'ALUMINIUM', 'Алюминий'
- CAST_IRON = 'CAST_IRON', 'Чугун'
- POLYESTER = 'POLYESTER', 'Полиэстер'
- PLA = 'PLA', 'PLA'
- ABS = 'ABS', 'ABS'
- PETG = 'PETG', 'PETG'
- weight = models.PositiveSmallIntegerField('Вес', default=0)
- material = models.CharField('Материал', choices=CompositionType.choices, default=CompositionType.PLA)
- def __str__(self):
- return f'{self.material} - {self.weight}'
- class Meta:
- db_table = 'characteristic'
- verbose_name = 'Характеристика'
- verbose_name_plural = 'Характеристики'
- class Customer(models.Model):
- """Покупатель"""
- user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
- # Где поля адреса фио и тд ???
- # Тут должна быть сылка на adress
- def __str__(self):
- return self.user.username
- class Meta:
- db_table = 'customer'
- verbose_name = 'Покупатель'
- verbose_name_plural = 'Покупатели'
- class Order(models.Model):
- """Заказ"""
- class Statuses(models.TextChoices):
- IN_PROCESSING = 'IN_PROCESSING', 'В обработке'
- ACCEPTED = 'ACCEPTED', 'Принята'
- PREPARED_FOR_SHIPMENT = 'PREPARED_FOR_SHIPMENT', 'Подготовлено к отправке'
- SENT = 'SENT', 'Отправлено',
- DELIVERED = 'DELIVERED', 'Доставлено'
- COMPLETED = 'COMPLETED', 'Завершен'
- product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, verbose_name='Продукт')
- user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name='Заказчик')
- date = models.DateTimeField('Дата заказа', default=datetime.now())
- count = models.SmallIntegerField('Количество', default=1)
- status = models.CharField('Статус', choices=Statuses.choices, default=Statuses.IN_PROCESSING)
- def __str__(self):
- return f'{self.product} - {self.date} - {self.count} - {self.status}'
- class Meta:
- db_table = 'order'
- verbose_name = 'Заказ'
- verbose_name_plural = 'Заказы'
- class Address(models.Model):
- """Адрес"""
- user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name='Пользователь') # Не верно !!!!! Адрес должен быть у пациента , но не у адрема есть пациент
- recipient = models.CharField('Получатель', max_length=250)
- phone = models.CharField('Номер телефона', max_length=50)
- country = models.CharField('Страна', max_length=150)
- city = models.CharField('Город', max_length=150)
- location = models.CharField('Дом, кв', max_length=250)
- zip = models.CharField('Почтовый индекс', max_length=25)
- def __str__(self):
- return f'{self.country}-{self.city}-{self.location}'
- class Meta:
- db_table = 'address'
- verbose_name = 'Адрес'
- verbose_name_plural = 'Адреса'
- class Post(models.Model):
- """Пост"""
- title = models.CharField('Заголовок', max_length=250)
- author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, verbose_name='Автор')
- preview = models.ImageField('Превью', upload_to='media/post_previews/')
- publish_date = models.DateTimeField('Дата публикации', default=datetime.now())
- tags = models.ManyToManyField('Tag', verbose_name='теги')
- text = models.TextField('Текст', max_length=1000)
- def __str__(self):
- return self.title
- class Meta:
- db_table = 'post'
- verbose_name = 'Пост'
- verbose_name_plural = 'Посты'
- class Tag(models.Model):
- name = models.CharField('Тег', max_length=25)
- url = models.SlugField('Ссылка', max_length=250, unique=True)
- def __str__(self):
- return self.name
- class Meta:
- db_table = 'tag'
- verbose_name = 'Тег'
- verbose_name_plural = 'Теги'
- class PostReview(models.Model):
- user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, blank=True, verbose_name='Пользователь')
- name = models.CharField('Имя', max_length=50)
- email = models.EmailField('Email', unique=True)
- text = models.TextField('Текст', max_length=500)
- post = models.ForeignKey(Post, on_delete=models.CASCADE, verbose_name='Пост')
- def __str__(self):
- return f'{self.name} - {self.post}'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement