-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathseed_db.py
More file actions
79 lines (65 loc) · 2.91 KB
/
seed_db.py
File metadata and controls
79 lines (65 loc) · 2.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""Базовый сидер базы данных."""
from decimal import Decimal
from database import SessionLocal
from Models import Category, Client, Nomenclature, Order, OrderItem
def seed_categories(db) -> None:
if db.query(Category).first():
return
root = Category(name="Товары", parent_id=None)
db.add(root)
db.flush()
db.add(Category(name="Электроника", parent_id=root.id))
db.add(Category(name="Одежда", parent_id=root.id))
db.add(Category(name="Канцтовары", parent_id=root.id))
def seed_nomenclature(db) -> None:
if db.query(Nomenclature).first():
return
cat = db.query(Category).filter(Category.name == "Электроника").first()
cat_id = cat.id if cat else None
db.add_all([
Nomenclature(name="Мышь", quantity=50, price=Decimal("599.00"), category_id=cat_id),
Nomenclature(name="Клавиатура", quantity=30, price=Decimal("1299.00"), category_id=cat_id),
Nomenclature(name="Наушники", quantity=25, price=Decimal("2499.00"), category_id=cat_id),
])
cat_office = db.query(Category).filter(Category.name == "Канцтовары").first()
office_id = cat_office.id if cat_office else None
db.add_all([
Nomenclature(name="Блокнот", quantity=100, price=Decimal("150.00"), category_id=office_id),
Nomenclature(name="Ручка", quantity=200, price=Decimal("25.00"), category_id=office_id),
])
def seed_clients(db) -> None:
if db.query(Client).first():
return
db.add_all([
Client(name="ООО Ромашка", address="г. Москва, ул. Ленина, д. 1"),
Client(name="ИП Иванов", address="г. Санкт-Петербург, Невский пр., д. 10"),
Client(name="ООО Тест", address="г. Казань, ул. Баумана, д. 5"),
])
def seed_orders(db) -> None:
if db.query(Order).first():
return
client = db.query(Client).first()
nom1 = db.query(Nomenclature).filter(Nomenclature.name == "Мышь").first()
nom2 = db.query(Nomenclature).filter(Nomenclature.name == "Блокнот").first()
if not client or not nom1 or not nom2:
return
order = Order(client_id=client.id)
db.add(order)
db.flush()
db.add(OrderItem(order_id=order.id, nomenclature_id=nom1.id, quantity=2, price=nom1.price))
db.add(OrderItem(order_id=order.id, nomenclature_id=nom2.id, quantity=5, price=nom2.price))
def seed_db() -> None:
db = SessionLocal()
try:
seed_categories(db)
db.commit()
seed_nomenclature(db)
seed_clients(db)
db.commit()
seed_orders(db)
db.commit()
finally:
db.close()
if __name__ == "__main__":
seed_db()
print("База данных заполнена (seed выполнен).")