Search code examples
pythondjangoapidjango-rest-frameworkmodels

generate a Django-REST-API directly ?


I have already a database that contains 100 tables.

Now, I would like to expose it as a REST-API.

I've done this before so I am familiar with the procedure. I create a serializer for the model, a ViewSet for the Serialiizer and an a router. I test it on 2 tables and it works.

The problem is that I want to expose all my 100 tables. And doing the same prcedure 100 times is no fun.

Is there a way to do it only one time?


Solution

  • It appears there is no way to do so in django.

    NOW, THIS IS NOT THE BEST SOLUTION,

    SOMETIMES, DIFFERENT SERIALIZERS CLASSES ARE NEEDED DEPENDING ON RELATIONS

    I just created a script that works:

    You just need to run it from your project directory with your app name as an argument

    `import os
    import sys
    
    ROUTER_TEMPLATE = "router.register(r'{}', views.{}ViewSet)"
    SERIALIZER_TEMPLATE = """
    class {}Serializer(serializers.HyperlinkedModelSerializer):
    
        class Meta:
            model = {}
            fields = '__all__'
    """
    VIEW_TEMPLATE= """
    
    class {}ViewSet(viewsets.ModelViewSet):
        queryset = {}.objects.all()
        serializer_class = {}Serializer
    
    
    """
    
    def gen_api(app_name):
            models= open(app_name+'/models.py', 'r')
        aLines = models.readlines()
    
        for sLine in aLines:
    
            aLine = sLine.split()
    
            for sWord in aLine:
    
                if sWord == "class" and aLine[aLine.index(sWord)+1] != "Meta:":
                    model_name= aLine[aLine.index(sWord)+1].split("(")[0]
                    gen(app_name,model_name )
    
    
    
    
    def gen(app_name, name):
    
        config = open(app_name+'/urls.py', 'a') #append
        config.write("\n"+ ROUTER_TEMPLATE.format(name, name))
        config.close()
    
        config = open(app_name+'/serializers.py', 'a') #append
        config.write("\n"+ SERIALIZER_TEMPLATE.format(name, name))
        config.close()
    
        config = open(app_name+'/views.py', 'a') #append
        config.write("\n"+ VIEW_TEMPLATE.format(name, name, name))
        config.close()
    
    if __name__ == "__main__":
    
        gen_api(sys.argv[1])
    `