Dynamic models

10 views
Skip to first unread message

ruth salvatore

unread,
May 22, 2023, 5:34:01 PM5/22/23
to Django users
Here I am creating django dynamic models but for getting  data i am using get method but i am not getting data it just says that table does not exist even if it is present.

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

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']

# 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:
field_class=FIELD_TYPE[field_type](max_length=max_length)
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['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)})
Reply all
Reply to author
Forward
0 new messages