0

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; 
palamunder
  • 2,555
  • 1
  • 19
  • 20
  • Possible duplicate of [Django: dynamic database file](https://stackoverflow.com/questions/14254315/django-dynamic-database-file) – Selcuk Oct 11 '18 at 02:03
  • @Selcuk the proposed solution is for another databse, not for another table. The solution proposed there does not solve this problem – palamunder Oct 11 '18 at 06:09

1 Answers1

0

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) 
 ...
palamunder
  • 2,555
  • 1
  • 19
  • 20