Single Django model, multiple tables?

后端 未结 2 716
失恋的感觉
失恋的感觉 2020-11-29 22:01

I have several temporary tables in a MySQL database that share the same schema and have dynamic names. How would I use Django to interface with those tables? Can a single mo

2条回答
  •  甜味超标
    2020-11-29 22:12

    Create a model for your table dynamically.

    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
    

    and you can start querying the database.

    In [6]: t = create_model('trial1')
    
    In [7]: t._meta.db_table
    Out[7]: 'trial1'
    
    In [8]: t.objects.all()  # default db
    Out[8]: [, '(remaining elements truncated)...']
    
    In [9]: t.objects.using('test').all()  # test db
    Out[9]: [, '(remaining elements truncated)...']
    

提交回复
热议问题