tortoise-orm icon indicating copy to clipboard operation
tortoise-orm copied to clipboard

Can tablename be determined at runtime?

Open david9100 opened this issue 4 years ago • 7 comments

In my database I have lookup tables assigned to each customer. Each of these lookup tables share the same model. Is it possible to define a single model and then determine the tablename at runtime?

david9100 avatar Feb 05 '21 17:02 david9100

add a new column customer maybe better

long2ice avatar Feb 06 '21 01:02 long2ice

same here, the same model applies to different tables with the same schema. would like a way to do it.

JooDye avatar Oct 13 '24 01:10 JooDye

@Jasdent Do you mean the table name can change multiple times while the app is running, or initialise it to a different name on each run?

Abdeldjalil-H avatar Nov 15 '24 06:11 Abdeldjalil-H

@Abdeldjalil-H yes, an example call would be like this:

await ObjectReadings.Table(tbl_name).filter(...).order_by(...)

JooDye avatar Nov 15 '24 09:11 JooDye

Interseting. Can you please give a real world scenario where this can be used? Why will someone choose this approach instead of creating an abstract model and inherit from it to get the needed tables? Something like this:

class BaseObjectReadings(Model):
    class Meta:
        abstract = True
    
class FirstModel(BaseObjectReadings):
    pass

class SecondModel(BaseObjectReadings):
    pass

Abdeldjalil-H avatar Nov 15 '24 10:11 Abdeldjalil-H

@Abdeldjalil-H Scenario would be IoT edge computing, where there are time series data flowing from each device, so I decided to make a table for each device's readings (having a column of deviceID instead is not gonna be performant enough to run our system). When I register a device with an API in the system, a table is created based on the device ID and devices might come and go on the run. I understand time series db might be a better alternative in the long term, but here we are at the moment.

Having derived class from the abstract is not gonna do the job because it requires code edition and code is not gonna change on the run. I have tried having a function that returns a derived class with table name based on the function input, but it couldn't work as I guess it had something to do with Tortoise.init, it cannot deal with classes generated after init.

JooDye avatar Nov 16 '24 01:11 JooDye

@Abdeldjalil-H any updates on whether there will be a feature to be planned for this?

JooDye avatar Nov 21 '24 01:11 JooDye