One Django model, multiple tables?

I know that the same question was asked earlier, but I was hoping for a "better" answer (which does not include modifying class attributes at runtime). It was a question:

Single Django model, multiple tables?

I have the same problem. I am looking for a solution similar to the defendant's first answer, but it really works. If there is no better solution, can anyone comment on how reliable the defendant’s decision is? It seems to me that the delay between changing the database name and the database query can lead to the return of results from the wrong table:

request 1: change name

query 2: change name again

query 1: get results (but using the wrong name from query 2)

Edit: the model is intended for use on ~ 15 tables - therefore, inheritance is impractical, since each time a new model name is required.

thanks

PS We apologize if this is not the right way to ask for a question.

+7
source share
1 answer

for a dynamic table and interchangeability model of a database with sexier behavior than in your related question, you can use simple methods or properties:

import copy class MyModel(models.Model): # anything @property def table_name(self): return self._meta.db_table @table_name.setter def table_name(self, value): new_meta = copy.copy(self._meta) new_meta.db_table = value self._meta = new_meta @classmethod def set_qs_for_table(cls, qs, table): my_class = copy.copy(cls) my_options = copy.copy(my_class._meta) my_class._meta = my_options qs.model = my_class 

You can try something like this ...

Copy part to avoid the danger of common options between models. It took me a while to find this part of the solution. but for the rest it looks sexy and simple.

Of course, once in python code you can use

 qs = MyClass.objects.all() MyClass.set_qs_for_table(qs, "this_table") my_instance = qs[0] my_instance.table_name = "that_table" my_instance.save(using="this_db") 
+2
source

All Articles