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
--
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.
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!')
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAMJ3z%3D3Qn0n%2BHVefJg_B6R9RQABA88C4whqbn0g3ygo4k0gkMw%40mail.gmail.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAO-ToNUai69i86uMD6-Z%2BSZha9DpjHSSbNFBGcwpf19N4eEtnw%40mail.gmail.com.
--