简体   繁体   English

具有动态数据库表的Django模型

[英]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. 我正在使用Django与另一个(JAVA)应用程序接口,该应用程序基于某些事件在运行时在具有相同模型的数据库表中生成。 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: 目前,我的Django模型看起来像这样:

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: 其他可能性也可能是使SQL查询在不同的表上执行,因此可能类似于:

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: 到目前为止,似乎最好的解决方案是进行自定义SQL查询,因此在此示例中,在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) 
 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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