🎉 سال نو، مهارت نو، مشاوره رایگان نقشه راه برنامه نویسی (آفر ویژه ثبت نام قبل از افزایش قیمت 🔥)
۰ ثانیه
۰ دقیقه
۰ ساعت
۱ Seyed Mohammad Jafa
درست کردن جدول در دیتابیس با استفاده از لیست پایتونی
جامعه پایتون (وب) ایجاد شده در ۱۸ مرداد ۱۴۰۲

سلام. چطور میشه تابع زیر رو کامل کرد؟

تابعی بنویسیم که یک لیستی از نام‌های جداول رو بگیره و در دیتا بیس ذخیره کنه. بطوری که کلاس‌های هر مدل رو این تابع خودش خودکار بسازه و از هر کلاس یک نمونه در اختیار ما برای کار با دیتابیس قرار بده.

import peewee
def table_creator(table_names):
          instances = {}
          for table_name in table_names:
                         #Create an instance of a class and add it to the instance variable and store it in mysql
if __name__ == "__main__":
        tabel_names = ['table1', 'table2', 'table3']
        models = table_creator(table_names)
        for model in models :
                    model.create(value='data')

درود وقت بخیر

اصولا بخاطری اینکه دیتابیس هایی مثل postgre یا mysql تمایل دارن که جدول هارو به صورت Atomic اجرا بکنن شاید این کار زیاد درست نباشه ( به نظرم) و مسئله بعد اینکه باید ویژگی یا همون property ( column) هر table رو مشخص کنی

که البته با یه map ساده میشه تا حدودی هندلش کرد

import peewee
from playhouse.pool import PooledMySQLDatabase
# Define a Peewee MySQL database connection
db = PooledMySQLDatabase('my_database', user='your_username', password='your_password', host='localhost')
# Base model class
class BaseModel(peewee.Model):
    class Meta:
        database = db
# Function to dynamically create models
def table_creator(table_names):
    models = []
    for table_name in table_names:
        # Define a new Peewee model dynamically, set attributes
        model_class = type(table_name, (BaseModel,), {
            'value': peewee.CharField(max_length=255)
        })
        models.append(model_class)
        # Create the table in the database
        db.create_tables([model_class])
    return models
if __name__ == "__main__":
    table_names = ['table1', 'table2', 'table3']
    models = table_creator(table_names)
    for model in models:
        with db.atomic():
            model.create(value='data')

موفق باشید ?

بهترین پاسخ
Reza Mobaraki ۱۹ مرداد ۱۴۰۲، ۰۸:۵۹