Dynamically updating db_table to use one model for several database tables
I thought I ran into a roadblock with Django that would require writing raw SQL to resolve instead of using Django's ORM. I asked about it on SO and was informed it is possible to create dynamic classes or to assign
db_table dynamically to the model.
The issue is that I have several dozen tables that are similar. They do all have about five fields that are in them all. The remaining hundred, or so columns, are unique. (Basically each table represents industry data and a year; even within the same industry the data can vary from year to year). I was informed that Django models are pretty "loose" in that you could only identify these common columns and the model doesn't care about the rest of the columns, so you could do a
Table.objects.all() and get everything in the table.
My concern was I was going to need to build several dozen mostly redundant models, and have to add new ones annually which is really inefficient. I was leaning towards writing the query in raw SQL so I could dynamically specify the table name until I was informed of these things.
Came across these SO questions, but I am really not understanding how to implement using Django REST Framework.
So in my
serializers.py I know I would need to do something like:
./serializers.py from rest_framework import serializers from .models import GenericModel class IndustryDataSerializer(serializers.ModelSerializer): # logic to determine the correct db_table might go here class Meta: model = # Need to pass db_table here I assume fields = [ __all__ ]
And the model would just be built as normal:
./models.py from django.db import models class GenericModel(models.Model): common_field_1 = models... common_field_2 = models... common_field_3 = models... common_field_4 = models... common_field_5 = models... class Meta: db_table = # Need to pass in the db_table # maybe the logic to determine the db_table goes here in a method
This should, I think, serialize the entire table and pass it to the FE.
Anyway, what I am not connecting the dots together on is how to pass in the dynamic
The second SO question raises seems to indicate it isn't safe to do this, so the question is also what is the proper method for passing in the
db_table to the model.