我正在尝试使用Django框架实现Rest api。但是,当我单击默认索引页面上的url时,它在/ languages / Class LanguageSerializer缺少meta.model属性时给了我一个断言错误
在更改models.py之后,我进行了所有迁移,但是它什么也没做
urls.py
from django.urls import path, include
from . import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register('languages', views.LanguageView)
urlpatterns = [
path('', include(router.urls))
]
models.py
from django.db import models
class Language(models.Model):
name = models.CharField(max_length=50)
paradigm = models.CharField(max_length=50)
serializers.py
from rest_framework import serializers
from .models import Language
class LanguageSerializer(serializers.ModelSerializer):
class Meta:
fields = ('id', 'name', 'paradigm')
views.py
from django.shortcuts import render
from rest_framework import viewsets
from .models import Language
from .serializers import LanguageSerializer
class LanguageView(viewsets.ModelViewSet):
queryset = Language.objects.all()
serializer_class = LanguageSerializer
我不知道我要去哪里错了
答案 0 :(得分:3)
您需要在序列化程序的Meta
类中指定要序列化的模型,例如:
from rest_framework import serializers
from .models import Language
class LanguageSerializer(serializers.ModelSerializer):
class Meta:
model = Language # specify the model
fields = ('id', 'name', 'paradigm')
否则,序列化程序将无法确定该模型的字段,以及如何将这些字段中的数据序列化。