Skip to content

Commit

Permalink
Merge pull request #18 from healthy-food-and-dietary-products/feature…
Browse files Browse the repository at this point in the history
…/orders

Feature/orders
  • Loading branch information
earlinn authored Oct 19, 2023
2 parents 47f7deb + f368588 commit a002706
Show file tree
Hide file tree
Showing 12 changed files with 273 additions and 0 deletions.
43 changes: 43 additions & 0 deletions backend/api/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from orders.models import ShoppingCart
from rest_framework import serializers


class ShoppingCartListSerializer(serializers.ModelSerializer):
"""Serializer for product representation."""
product_name = serializers.SerializerMethodField()
product_amount = serializers.SerializerMethodField()
product_price = serializers.SerializerMethodField()

class Meta:
model = ShoppingCart
fields = ('product_name', 'product_amount', 'product_price')

def get_product_name(self, obj):
return obj.product.name

def get_product_amount(self, obj):
return obj.product.amount

def get_product_price(self, obj):
return obj.product.price


class ShoppingCartPostUpdateSerializer(serializers.ModelSerializer):
count_of_product = serializers.IntegerField(default=1)

class Meta:
fields = '__all__'
model = ShoppingCart
validators = (
serializers.UniqueTogetherValidator(
queryset=ShoppingCart.objects.all(),
fields=('user', 'product'),
message='Вы уже добавили этот продукт в корзину!'
),
)

def validate_count_of_product(self, data):
if data < 1:
raise serializers.ValidationError(
'Количество товара в корзине должно быть не меньше 1!')
return data
Empty file added backend/api/urls.py
Empty file.
10 changes: 10 additions & 0 deletions backend/data/category.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
id,name,slug
1,Фрукты,fruts
2,Овощи,vegetables
3,Хлебобулочные изделия,bakery
4,Напитки,drinks
5,Молочные продукты,dairy
6,Безглютеновые продукты,gluten-free
7,Безлактозные продукты,lactose-free
8,Мясная продукция,meat
9,Птица,poultry
4 changes: 4 additions & 0 deletions backend/data/products.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
id,name,measure_unit,amount,description,image,producer,category,price
1,авокадо,гр,50,Спелое авокадо,avocado.jpg,TLC,2,50
2,огурцы,гр,200,Огурцы гладкие,cucumbers.jpg,TLC,2,60
3,Чай зеленый Молочный Улунг,гр,150,Зеленый чай,green_tea.jpg,TLC,4,300
7 changes: 7 additions & 0 deletions backend/data/users.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
id,username,email,password,first_name,last_name,address
2,vasya.pupkin,vasya@yandex.ru,Qwerty123poiu,Вася,Пупкин,Saint-Petersburg
3,july.kol,kolkinaa@mail.ru,mnbvcxz12345,Юля,Колкина,Saint-Petersburg
4,nastya.vasina,nastya@yandex.ru,1234Qwerty987,Настя,Васина,Saint-Petersburg
5,kisa.mura,kisa@yandex.ru,mnjggffdfdf,Кира,Муравьева,Saint-Petersburg
6,Kostya.Smirny,smirnov@yandex.ru,smirnuy098876,Константин,Смирнов,Saint-Petersburg
7,sonya.and,andr@mail.ru,andr0987,Соня,Андреева,Saint-Petersburg
1 change: 1 addition & 0 deletions backend/good_food/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
"products.apps.ProductsConfig",
"users.apps.UsersConfig",
"api.apps.ApiConfig",
"orders.apps.OrdersConfig",
"phonenumber_field",
]

Expand Down
Empty file added backend/orders/__init__.py
Empty file.
9 changes: 9 additions & 0 deletions backend/orders/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django.contrib import admin
from orders.models import ShoppingCart


@admin.register(ShoppingCart)
class ShoppingCartAdmin(admin.ModelAdmin):
list_display = ('id', 'user', 'product', 'quantity', 'status')
list_editable = ('user', 'product', 'quantity')
search_fields = ('user',)
6 changes: 6 additions & 0 deletions backend/orders/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class OrdersConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'orders'
Empty file.
111 changes: 111 additions & 0 deletions backend/orders/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models

from products.models import Product
from users.models import User


class ShoppingCart(models.Model):
"""Model for creating a shopping cart."""

SHOPPINGCART = (('Ordered', 'Передано в заказ'),
('In work', 'В работе'))

user = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='shopping_carts',
verbose_name='Добавил в корзину'
)
product = models.ForeignKey(
Product,
on_delete=models.CASCADE,
related_name='shopping_carts',
verbose_name='Продукт в корзине'
)
quantity = models.IntegerField(
verbose_name='Количество товара',
validators=[
MinValueValidator(1, 'Разрешены значения от 1 до 100'),
MaxValueValidator(10000, 'Разрешены значения от 1 до 100')
]
)
status = models.CharField(
max_length=50,
choices=SHOPPINGCART,
default='В работе'
)

class Meta:
verbose_name = 'Корзина'
verbose_name_plural = 'Корзина'
constraints = [
models.UniqueConstraint(
fields=['user', 'product'],
name='unique_shopping_cart'
)
]


class Order(models.Model):
"""Model for creating an order."""

STATUS = (('Ordered', 'Оформлен'),
('In processing', 'В обработке'),
('Completed', 'Комплектуется'),
('Gathered', 'Собран'),
('In delivering', 'Передан в доставку'),
('Delivered', 'Доставлен'),
('Completed', 'Завершен'))

PAYMENT_METHODS = (('Cash', 'Наличные'),
('By card on the website', 'Картой на сайте'),
('In getting', 'При получении'))

DELIVERY_METHOD = (('Point of delivery', 'Пункт выдачи'),
('By courier', 'Курьером'))

user = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='orders',
verbose_name='Покупатель'
)
goods = models.ForeignKey(
ShoppingCart,
on_delete=models.CASCADE,
related_name='orders',
verbose_name='Покупки'
)
date = models.DateField(
verbose_name='Дата оформления',
auto_now_add=True
)
status = models.CharField(
max_length=50,
choices=STATUS,
default='Оформлен'
)
payment_method = models.CharField(
max_length=50,
choices=PAYMENT_METHODS,
default='Картой на сайте'
)
is_paid = models.BooleanField(default=False)
comment = models.TextField(
max_length=400,
blank=True
)
delivery_method = models.CharField(
max_length=50,
choices=DELIVERY_METHOD,
default='Курьером'
)
total_price = models.IntegerField(
default=0
)

class Meta:
ordering = ['-date']
verbose_name = 'Заказ'
verbose_name_plural = 'Заказы'
82 changes: 82 additions & 0 deletions backend/products/management/commands/load_data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import csv
import os

from django.conf import settings
from django.core.management.base import BaseCommand

from products.models import Category, Product
from users.models import User


def read_users():
with open(os.path.join(settings.BASE_DIR, 'data', 'users.csv'),
'r', encoding='utf-8') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
if row[0] == 'id':
continue
User.objects.get_or_create(
id=row[0],
username=row[1],
email=row[2],
password=row[3],
first_name=row[4],
last_name=row[5],
# role=row[6]

)
print('Данные из файла users.csv загружены')


def read_category():
with open(
os.path.join(
settings.BASE_DIR,
'data', 'category.csv',
),
'r', encoding='utf-8'
) as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
if row[0] == 'id':
continue
Category.objects.get_or_create(
id=row[0],
name=row[1],
slug=row[2],
)
print('Данные из файла category.csv загружены')


def read_products():
with open(
os.path.join(
settings.BASE_DIR,
'data', 'products.csv',
),
'r', encoding='utf-8'
) as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
if row[0] == 'id':
continue
Product.objects.get_or_create(
id=row[0],
name=row[1],
measure_unit=row[2],
amount=row[3],
description=row[4],
image=row[5],
producer=row[6],
category=row[7],
price=row[8]
)
print('Данные из файла products.csv загружены')


class Command(BaseCommand):

def handle(self, *args, **options):
read_users()
read_category()
read_products()

0 comments on commit a002706

Please sign in to comment.