我在一个MySQL数据库中有几个临时表,它们共享相同的模式并具有动态名称。如何使用Django与这些表进行交互?单个模型可以从多个表中绘制数据吗?
发布于 2015-04-02 18:43:05
为您的表动态创建模型。
from django.db import models
from django.db.models.base import ModelBase
def create_model(db_table):
class CustomMetaClass(ModelBase):
def __new__(cls, name, bases, attrs):
model = super(CustomMetaClass, cls).__new__(cls, name, bases, attrs)
model._meta.db_table = db_table
return model
class CustomModel(models.Model):
__metaclass__ = CustomMetaClass
# define your fileds here
srno = models.IntegerField(db_column='SRNO', primary_key=True)
return CustomModel你就可以开始查询数据库了。
In [6]: t = create_model('trial1')
In [7]: t._meta.db_table
Out[7]: 'trial1'
In [8]: t.objects.all() # default db
Out[8]: [<CustomModel: CustomModel object>, '(remaining elements truncated)...']
In [9]: t.objects.using('test').all() # test db
Out[9]: [<CustomModel: CustomModel object>, '(remaining elements truncated)...']https://stackoverflow.com/questions/5036357
复制相似问题