Сделали BaseModel
This commit is contained in:
@@ -2,9 +2,50 @@ import sqlite3
|
||||
|
||||
db_name = 'mydb.db'
|
||||
|
||||
class User:
|
||||
def __init__(self,name,email,age):
|
||||
self.__id = None
|
||||
class BaseModel:
|
||||
def __init__(self,id):
|
||||
self.__id = id
|
||||
|
||||
@classmethod
|
||||
def get_by_id(cls,id):
|
||||
conn = sqlite3.connect(db_name)
|
||||
cursor = conn.cursor()
|
||||
property_list = ['id']+[f"{k}" for k, v in cls.__dict__.items() if isinstance(v, property)]
|
||||
property_string = ','.join(property_list)
|
||||
query = f"SELECT {property_string} FROM {cls.__name__} WHERE id = ?"
|
||||
cursor.execute(query,(id,))
|
||||
result = cursor.fetchone()
|
||||
property_dict = dict()
|
||||
for index in range(len(property_list)):
|
||||
property_dict[property_list[index]] = result[index]
|
||||
conn.close()
|
||||
return cls(**property_dict)
|
||||
|
||||
def save(self):
|
||||
conn = sqlite3.connect(db_name)
|
||||
cursor = conn.cursor()
|
||||
property_list = [f"{k}" for k, v in self.__class__.__dict__.items() if isinstance(v, property)]
|
||||
|
||||
if self.__id != None:
|
||||
update_string = ','.join([f'`{p_name}`= ? ' for p_name in property_list])
|
||||
update_values = [getattr(self,p) for p in property_list] + [self.__id]
|
||||
query = f"UPDATE {self.__class__.__name__} SET {update_string} WHERE id = ?"
|
||||
print(query,update_values)
|
||||
cursor.execute(query,update_values)
|
||||
conn.commit()
|
||||
else:
|
||||
property_count = ('?,'*len(property_list))[:-1]
|
||||
property_names = ','.join(property_list)
|
||||
property_values = [getattr(self,p) for p in property_list]
|
||||
query = f"INSERT INTO {self.__class__.__name__}({property_names}) VALUES({property_count})"
|
||||
cursor.execute(query,property_values)
|
||||
conn.commit()
|
||||
self.__id = cursor.lastrowid
|
||||
conn.close()
|
||||
|
||||
class User(BaseModel):
|
||||
def __init__(self,name,email,age,id = None):
|
||||
super().__init__(id)
|
||||
self.__name = name
|
||||
self.__email = email
|
||||
self.__age = age
|
||||
@@ -35,29 +76,31 @@ class User:
|
||||
self.__age = value
|
||||
else:
|
||||
raise ValueError('Неправильно указан возраст')
|
||||
|
||||
def save(self):
|
||||
conn = sqlite3.connect(db_name)
|
||||
cursor = conn.cursor()
|
||||
property_list = [f"{k}" for k, v in User.__dict__.items() if isinstance(v, property)]
|
||||
if '_User__id' in self.__dict__.keys():
|
||||
update_string = ','.join([f'`{p_name}`= ? ' for p_name in property_list])
|
||||
update_values = [getattr(self,p) for p in property_list] + [self.__id]
|
||||
query = f"UPDATE {User.__name__} SET {update_string} WHERE id = ?"
|
||||
print(query,update_values)
|
||||
else:
|
||||
property_count = ('?,'*len(property_list))[:-1] #','.join(['?' for _ in range(len(property_list))])
|
||||
property_names = ','.join(property_list)
|
||||
property_values = [getattr(self,p) for p in property_list]
|
||||
query = f"INSERT INTO {User.__name__}({property_names}) VALUES({property_count})"
|
||||
print(query,property_values)
|
||||
cursor.execute(query,property_values)
|
||||
conn.commit()
|
||||
self.__id = cursor.lastrowid
|
||||
conn.close()
|
||||
#print(User.__dict__)
|
||||
|
||||
class Product(BaseModel):
|
||||
def __init__(self,name,category,price,id=None):
|
||||
super().__init__(id)
|
||||
self.__name = name
|
||||
self.__category = category
|
||||
self.__price = price
|
||||
@property
|
||||
def name(self):
|
||||
return self.__name
|
||||
@property
|
||||
def category(self):
|
||||
return self.__category
|
||||
@property
|
||||
def price(self):
|
||||
return self.__price
|
||||
|
||||
product1 = Product('Свинина, шея','Мясные продукты',250)
|
||||
product1.save()
|
||||
'''
|
||||
user2 = User.get_by_id(9)
|
||||
user2.name = 'Andrey'
|
||||
user2.save()
|
||||
user1 = User('Igor','igor@example.com',44)
|
||||
user1.save()
|
||||
user1.age = 55
|
||||
user1.save()
|
||||
'''
|
||||
|
||||
Reference in New Issue
Block a user