dynamic django tables

214 views
Skip to first unread message

Helly Modi

unread,
May 19, 2023, 9:00:31 AM5/19/23
to Django users

How to create dynamic models in django rest framework?

Is there any chance to create dynamic models with APIs

 

Any examples please send me thanks in advance..

 

1) Requirement is need create table name and fields in frontend

2) we are  getting the data and store in to the db create db structure

3) get the table name and fields create table in backend &postgresql store to

4)this code don't update or add into the models 

5)store the data into the tables 

Brian Gitau

unread,
May 19, 2023, 9:10:08 AM5/19/23
to django...@googlegroups.com
which code do you have or you want the code example explaining everything?


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/72d09483-5129-43e1-bdbb-7b92969d97c4n%40googlegroups.com.

Helly Modi

unread,
May 22, 2023, 1:20:51 AM5/22/23
to django...@googlegroups.com
class CreateTableAPIView(APIView):
def post(self, request):
serializer = CreateTableSerializer(data=request.data)
serializer.is_valid(raise_exception=True)

table_name = serializer.validated_data['table_name']
fields = serializer.validated_data['fields']

# Create a dynamic model class
dynamic_model_attrs = {'__module__': __name__}
for field in fields:
field_name=field['name']
field_type=field['type']
max_length=field.get('max_length',255)

if field_type=='char':
field_class=models.CharField(max_length=max_length)
elif field_type== 'integer':
field_class=models.IntegerField()
elif field_type=='boolean':
field_class=models.BooleanField()
else:
field_class=models.EmailField()
dynamic_model_attrs[field_name]=field_class


dynamic_model = type(table_name, (models.Model,), dynamic_model_attrs)

# Create the database table for the dynamic model
with connection.schema_editor() as schema_editor:
schema_editor.create_model(dynamic_model)

# Register the dynamic model with the app
apps.all_models['dynamic_tables_app'][table_name] = dynamic_model

return Response(f'Table "{table_name}" created successfully!')


Helly Modi

unread,
May 22, 2023, 1:21:43 AM5/22/23
to django...@googlegroups.com
This is my code and it worked in creating tables but here django provides 26 fields and many relation how can i include all ? If else become too complex .Is there any other way to do this

Brian Gitau

unread,
May 22, 2023, 1:29:08 AM5/22/23
to django...@googlegroups.com
Try this i am not so sure though but trying isn't bad...kindly give me the feedback after trying 


from django.apps import apps
from django.db import connection, models
from rest_framework.response import Response
from rest_framework.views import APIView

FIELD_TYPE_MAPPING = {
    'char': models.CharField,
    'integer': models.IntegerField,
    'boolean': models.BooleanField,
    'email': models.EmailField,
    # Add more field types here if needed

}

class CreateTableAPIView(APIView):
    def post(self, request):
        serializer = CreateTableSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        table_name = serializer.validated_data['table_name']
        fields = serializer.validated_data['fields']

        # Create a dynamic model class
        dynamic_model_attrs = {'__module__': __name__}
        for field in fields:
            field_name = field['name']
            field_type = field['type']
            max_length = field.get('max_length', 255)

            if field_type in FIELD_TYPE_MAPPING:
                field_class = FIELD_TYPE_MAPPING[field_type](max_length=max_length)
            else:
                raise ValueError(f"Invalid field type: {field_type}")

            dynamic_model_attrs[field_name] = field_class


        dynamic_model = type(table_name, (models.Model,), dynamic_model_attrs)

        # Create the database table for the dynamic model
        with connection.schema_editor() as schema_editor:
            schema_editor.create_model(dynamic_model)

        # Register the dynamic model with the app
        apps.all_models['dynamic_tables_app'][table_name] = dynamic_model

        return Response(f'Table "{table_name}" created successfully!')

Sebastian Jung

unread,
May 22, 2023, 2:07:52 AM5/22/23
to django...@googlegroups.com
Hello,

I take everytime a EAV implementation for this task. Hete a manual: https://django-eav2.readthedocs.io/en/latest/

I hope this helps you

--

Helly Modi

unread,
May 22, 2023, 8:23:46 AM5/22/23
to Django users
I have to create api where user can select the column and type and other argument and it will create table in database in django.now here we can't use models .so we have to create tables dynamically at run time.so first i use django dynamic model in order to create table .it created table in database but when we try to do other operation such as getting all the details of table .it is not working.for fetching the data i have used Get method by providing table name from user in api but in the output it shows table does not exist even if table is present.sometime it shows table but sometime it desn't show.Is there any other approach.please help

from django.db import models, connection
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from django.apps import apps
from.serializers import CreateTableSerializer

FIELD_TYPE = {

'char': models.CharField,
'integer': models.IntegerField,
'boolean': models.BooleanField,
'email': models.EmailField,
'text': models.TextField,
'float': models.FloatField,
'file': models.FileField,
'date': models.DateTimeField

}


class CreateTableAPIView(APIView):
def post(self, request):
serializer = CreateTableSerializer(data=request.data)
serializer.is_valid(raise_exception=True)

table_name = serializer.validated_data['table_name']
fields = serializer.validated_data['fields']
primary_key_field = serializer.validated_data.get('primary_key') # Retrieve the primary key field name

# Create a dynamic model class
dynamic_model_attrs = {'__module__': __name__}
dynamic_model_fields = {}


for field in fields:
field_name = field['name']
field_type = field['type']
max_length = field.get('max_length', 255)

if field_type in FIELD_TYPE:
field_class = FIELD_TYPE[field_type](max_length=max_length)
dynamic_model_fields[field_name] = field_class

if primary_key_field:
# Check if the specified primary key field exists in the fields list
if primary_key_field in dynamic_model_fields:
dynamic_model_fields[primary_key_field].primary_key = True
else:
return Response(f'The specified primary key field "{primary_key_field}" does not exist in the fields list.')

dynamic_model_attrs.update(dynamic_model_fields)

dynamic_model = type(table_name, (models.Model,), dynamic_model_attrs)

# Create the database table for the dynamic model
with connection.schema_editor() as schema_editor:
schema_editor.create_model(dynamic_model)

# Register the dynamic model with the app
apps.all_models['Tables'][table_name] = dynamic_model


return Response(f'Table "{table_name}" created successfully!')


class GetTableDataAPIView(APIView):
def get(self, request, table_name):
try:
# Get the dynamic model class
dynamic_model = apps.get_model('Tables', table_name)
print(table_name)
except LookupError:
return JsonResponse({'message': f'Table "{table_name}" does not exist.'}, status=404)

# Retrieve all data from the dynamic table
table_data = dynamic_model.objects.all().values()
print(table_data)

return JsonResponse({'table_name': table_name, 'data': list(table_data)})

ruth salvatore

unread,
May 22, 2023, 5:34:01 PM5/22/23
to Django users
it worked for me thanks.but if someone wants to add constraints like primary key,Foreign key and many more then how to do it.
Reply all
Reply to author
Forward
0 new messages