简体   繁体   中英

Convert live Django project to REST API project

What is the best way to convert the project from django to django rest framework?

I have live django project, which is completely working, but now it want to convert the project into REST API.

I made the rest api for project which has new classes and function for the rest api with (form verification and same logic) copy from the django class which has been implemented.

So there is duplication of logic, so is there any way to do not replicate the logic and make running both of the classes django and django rest framework?

Problem is when any update needed for any page then i have to code both side django and django rest framework, so there can be some mistake arise in copy.

One can create an API with Django using custom views but I advise one to use Django REST Framework (DRF) instead as it simplifies the process.

In short,

  1. Install DRF with pip install djangorestframework (add it as well to the INSTALLED_APPS in your settings.py file).
  2. Create a serializer per your needs (DRF has built-in serializers, like ModelSerializer). Note that OP can definitely use the models that OP already had in Django.
  3. Create the views ( DRF has generic views ) and specify the URLs to access the views.

Let's say one has an app named books . In order to ensure the code isn't mixed between Django and the API, create an api folder inside of the books app and you should have something like this

books
-...
-api
--__init__.py
--serializers.py
--views.py
--urls.py 

If OP wills, add reference to that urls.py in OPs main urls.py file,

urlpatterns = [
    # ...
    path('api/', include('books.api.urls', namespace='api')),
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM