django-rest_framework BUG

  • 时间:
  • 来源:互联网
  • 文章标签:

今天在学习django-rest-framework框架时出现一个BUG。项目结构如下

App中有一个Book Model,定义如下:

class Book(models.Model):
    b_name = models.CharField(max_length=32)

然后我在REST app中也建了一个Book,定义如下:

class Book(models.Model):
    b_name = models.CharField(max_length=32)
    b_price = models.FloatField(default=1.0)

REST中的Serializers.py如下:

from django.contrib.auth.models import User, Group
from rest_framework import serializers

from REST.models import Book


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url','username','email','groups')

class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ('url','name')

# book
class BookSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Book
        fields = ('url','b_name','b_price')

REST中的view函数如下:

from django.contrib.auth.models import User, Group
from django.shortcuts import render
from rest_framework import viewsets
# Create your views here.
from App.models import Book
from REST.Serializers import UserSerializer, GroupSerializer, BookSerializer


class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class GroupViewSet(viewsets.ModelViewSet):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer



class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

APP 和 Best 都在setting中加入了。

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'REST.apps.RestConfig',
    'App.apps.AppConfig',
]

项目主目录中的urls如下:

from django.conf.urls import url
from django.contrib import admin
from django.urls import path, include

from rest_framework.routers import DefaultRouter

from REST.views import UserViewSet, GroupViewSet, BookViewSet


router = DefaultRouter()
router.register(r'users',UserViewSet)
router.register(r'groups',GroupViewSet)
router.register(r'books',BookViewSet)


urlpatterns = [
    # path('admin/', admin.site.urls),
    # url(r'^cbv/',include('App.urls',namespace='cbv')),
    url(r'^rest/',include(router.urls)),
]

当我启动服务时,Rest获取的确是App中的那个Book model .百思不得其解。

本文链接http://www.taodudu.cc/news/show-647398.html