码迷,mamicode.com
首页 > Web开发 > 详细

django rest frame work 初步使用 >> root url 以及表关联

时间:2018-08-21 22:40:54      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:col   路径   erb   else   ora   img   分享图片   tail   ddr   

1. Models 里再添加一个表, 并有外建关联。

技术分享图片
from django.db import models


class Publisher(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):
        return self.name

    class Meta:
        verbose_name = "Table Publisher"
        verbose_name_plural = verbose_name

# 新建表
class Book(models.Model):
    title = models.CharField(max_length=32, verbose_name="Book Name")
    publisher = models.ForeignKey("Publisher", on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = "Table Book"
        verbose_name_plural = verbose_name
models.py

 

2. serializer 在添加一个序列化, 外建自动关联。 (HyperlinkedModelSerializer)

技术分享图片
from rest_framework import serializers
from helloworld.models import Publisher, Book


class PublisherSerializer(serializers.ModelSerializer):
    operator = serializers.ReadOnlyField(source="operator.username")

    class Meta:
        model = Publisher
        fields = (
            "id",
            "name",
            "address",
            "operator"
        )


class BookSerializer(serializers.HyperlinkedModelSerializer):
    # 这样就不用再对列重新定义了
    # publisher = serializers.StringForreField(****)

    class Meta:
        model = Book
        fields = (
            "id",
            "title",
            "publisher"
        )
serializers.py

 

3. views.py  在对于新表添加 BookList, BookDetail 视图。

技术分享图片
class BookList(generics.ListCreateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    permissions_classes = (permissions.IsAuthenticated,)


class BookDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    permissions_classes = (permissions.IsAuthenticated, )
views.py

 

4. urls.py 添加 新的路径

技术分享图片
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. 自动添加根路径,并且切分urls.py

(1) 在新的 app views  下,添加一个 api_root() 的方法。

技术分享图片
from rest_framework.reverse import reverse
from rest_framework.decorators import api_view


@api_view(["GET"])
def api_root(request):
    return Response({
        "publisher": reverse(publisher-list, request=request),
        "books": reverse("book-list", request=request)
    })
app/views.py

 

(2) 调整 项目的urls.py, 使用include.

技术分享图片
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path(admin/, admin.site.urls),
    path(api-auth/, include(rest_framework.urls, namespace=rest_framework)),

    path(helloworld/, include("helloworld.urls")),
]
project/urls.py

 

(3) 在app 下创建urls.py, 写具体路径。

技术分享图片
from django.urls import path
from helloworld import views

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"),

]
app/urls.py

 

django rest frame work 初步使用 >> root url 以及表关联

标签:col   路径   erb   else   ora   img   分享图片   tail   ddr   

原文地址:https://www.cnblogs.com/shuo-yang0459/p/9514484.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!