Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

python - Single Django model, multiple tables?

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 model draw data from multiple tables?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could, I believe, make a factory function that would return your model with a dynamic db_table.

def getModel(db_table):
  class MyClass(models.Model):
     # define as usual ...
     class Meta:
       db_table = db_table

  return MyClass

newClass = getModel('29345794_table')
newClass.objects.filter( ...

EDIT: Django does not create a new instance of the class's _meta attribute each time this function is called. Creating a new instance for _meta it is dependent upon the name of the class (Django must cache it somewhere). A metaclass can be used to change the name of the class at runtime:

def getModel(db_table):
  class MyClassMetaclass(models.base.ModelBase):
    def __new__(cls, name, bases, attrs):
      name += db_table
      return models.base.ModelBase.__new__(cls, name, bases, attrs)

  class MyClass(models.Model):
    __metaclass__ = MyClassMetaclass

    class Meta:
      db_table = db_table

  return MyClass

not sure if it can be set dynamically on an already-defined class. I haven't done this myself but it might work.

You can set this whenever.

>>> MyModel._meta.db_table = '10293847_table'
>>> MyModel.objects.all()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...