简体   繁体   中英

Django model with dynamic db tables

I am using Django to interface with another (JAVA) application that based on some events generates at runtime tables in the db with the same model. So I don't have a direct control over the DB. For example:

Sensor1
id | value | time
1      10      2018-10-11

Sensor2
id | value | time
1      12     2018-10-11

Currently, my Django model is looking something like this:

class Sensor(models.Model):
 value = models.IntegerField()
 time = models.DatetimeField()

 class Meta:
  managed = False
  db_table = "Sensor1"

Do you have any clue if I can set the model somehow to be able to gain the data from a different table based on the query? Ideally, something that would allow me to get the data in the fashion of:

config_tables=['Sensor1','Sensor2']

for table in config_tables:
 data = Sensor.objects.table(table).objects.all()
 ...

Other possibility might be also to have a SQL query that executes on different tables, so perhaps something like:

SELECT * FROM %s; 

It seems that the best solution so far is to make a custom SQL Query so in this example it could be something like this in models.py:

def get_all_parameters(db_table):
    return Parameters.objects.raw('SELECT * FROM %s' % db_table)

and call it as:

get_all_parameters('Sensor1')

or as:

TABLES = ['Sensor1', 'Sensor2']

for table in TABLES:
 parameters = get_all_parameters(table) 
 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM