Django Rest frame Work initial use >> root URL and Table Association

Source: Internet
Author: User

1. Add a table to the Models and have an external association.

 fromDjango.dbImportModelsclassPublisher (models. Model): Name= Models. Charfield (max_length=32, verbose_name="Publisher Name", unique=True) Address= Models. Charfield (max_length=128, verbose_name="Publisher Address") operator= Models. ForeignKey ("Auth. User", on_delete=models. CASCADE)def __str__(self):returnSelf.nameclassMeta:verbose_name="Table Publisher"verbose_name_plural=Verbose_name#New TableclassBook (models. Model): Title= Models. Charfield (max_length=32, verbose_name="Book Name") Publisher= Models. ForeignKey ("Publisher", on_delete=models. CASCADE)def __str__(self):returnSelf.titleclassMeta:verbose_name="Table Book"verbose_name_plural= Verbose_name
models.py

2. Serializer is adding a serialization, built-in auto-correlation. (Hyperlinkedmodelserializer)

 fromRest_frameworkImportserializers fromHelloworld.modelsImportPublisher, BookclassPublisherserializer (serializers. Modelserializer): operator= serializers. Readonlyfield (source="Operator.username")    classMeta:model=Publisher Fields= (            "ID",            "name",            "Address",            "operator"        )classBookserializer (serializers. Hyperlinkedmodelserializer):#so you don't have to redefine the column.    #publisher = serializers. Stringforrefield (* * *)    classMeta:model= book Fields= (            "ID",            "title",            "Publisher"        )
serializers.py

3. views.py add Booklist to the new table, Bookdetail view.

class Booklist (generics. Listcreateapiview):    = Book.objects.all ()    = bookserializer    = (permissions. IsAuthenticated,)class  bookdetail (generics. Retrieveupdatedestroyapiview):    = Book.objects.all ()    = Bookserializer    = (Permissions. IsAuthenticated,)
views.py

4. urls.py Add a new path

Urlpatterns =[Path ("', Views.api_root), Path ('p/', views. Publisherlist.as_view (), name="publisher-list"), Path ('p/<int:pk>/', views. Publisherdetail.as_view (), name="Publisher-detail"), Path ('b /', views. Booklist.as_view (), name='book-list'), Path ('b/<int:pk>/', views. Bookdetail.as_view (), name="Book-detail"),]
urls.py

Part 2. Add root path automatically, and slice urls.py

(1) Under the new app views, add a Api_root () method.

 fromRest_framework.reverseImportReverse fromRest_framework.decoratorsImportApi_view@api_view (["GET"])defApi_root (Request):returnResponse ({"Publisher": Reverse ('publisher-list', request=request),"Books": Reverse ("book-list", request=request)})
app/views.py

(2) Adjust the urls.py of the project and use include.

 fromDjango.contribImportAdmin fromDjango.urlsImportPath, Includeurlpatterns=[Path ('admin/', Admin.site.urls), Path ('api-auth/', Include ('Rest_framework.urls', namespace='rest_framework')), Path ('helloworld/', Include ("Helloworld.urls")),]
project/urls.py

(3) Create a urls.py in the app and write the specific path.

 fromDjango.urlsImportPath fromHelloWorldImportViewsurlpatterns=[Path ("', Views.api_root), Path ('p/', views. Publisherlist.as_view (), name="publisher-list"), Path ('p/<int:pk>/', views. Publisherdetail.as_view (), name="Publisher-detail"), Path ('b /', views. Booklist.as_view (), name='book-list'), Path ('b/<int:pk>/', views. Bookdetail.as_view (), name="Book-detail"),]
app/urls.py

Django Rest frame Work initial use >> root URL and Table Association

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.