Django Rest Framework中的NameError,它显示我的模型名称未定义

时间:2019-06-26 08:22:42

标签: django python-3.x django-models django-rest-framework django-views

我正在尝试序列化数据库中的数据,以便可以访问客户端应用程序上的数据。 我刚接触Django仅1个月。 请帮我。 解决此问题的正确方法是什么? 我只希望它以JASON格式在数据中生成。 这给了我一个错误。 我在这里做错了什么? 不是吗?

此错误:

/ p / jobcardJobcard-ViewSet /中的

NameError 名称“工作卡”未定义 请求方法:GET 要求网址:http://127.0.0.1:8000/api/jobcardJobcard-ViewSet/ Django版本:2.2 异常类型:NameError 异常值:
名称“工作卡”未定义 异常位置:列表第16行中的/vagrant/jobcard_api/views.py Python可执行文件:/ home / vagrant / beanalyticenv / bin / python3

我尝试过使用Jobcard作为我的模型名称的方法

from jobcard_api.models import Jobcard

然后给出一个新的错误NameError

name 'JobcardSerializer' is not defined"

这是我在应用程序内的models.py,并且该应用程序在项目内,有三个应用程序,所有这些应用程序使用不同的名称给出相同的错误

from django.db import models
class Jobcard(models.Model):
    """Database model for the jobcard"""
    id = models.AutoField(primary_key=True)
    jobcard_number = models.CharField(max_length=30, unique=True, blank=False), ..., observation = models.TextField(blank=True)
    def get_jobcard_number(self):
        """Retrieve jobcard number"""
        return self.equipment_name

这是我在一个名为jobcard_api的应用程序中的serializers.py。

from rest_framework import serializers
from jobcard_api import models
class JobcardSerializer(serializers.ModelSerializer):
    """Serializer for the jobcard object"""
    class Meta:
        model = models.Jobcard
        fields = ('id', 'jobcard_number')
class DetailedJobcardSerializer(serializers.ModelSerializer):
    """Serializes the details of jobcard"""
    class Meta:
        model = models.Jobcard
        fields = ('id', 'jobcard_number',.., 'observation')
    def create(self, validated_data):
        """Create and return a new jobcard details"""
        jobcard = models.Jobcard.objects.create_jobcard(
            jobcard_number=validated_data['jobcard_number'],
            date_of_jobcard=validated_data['date_of_jobcard'],
            ..., observation=validated_data['observation']
        )
        return jobcard

这是我在名为jobcard_api的应用程序中的views.py。

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import viewsets
from jobcard_api import serializers
from jobcard_api import models

class JobcardViewSet(viewsets.ViewSet):
    """Jobcard API ViewSet"""
    serializer_class = serializers.JobcardSerializer
    def list(self, request):
        """Returns a list of Data from databse"""
        jobcard_api = Jobcard.objects.all()
        serializer = JobcardSerializer(jobcard_api, many=True)
        return Response(serializer.data)
    def create(self, request):
        """Create new data in  databse"""
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(
                serializer.errors,
                status=status.HTTP_400_BAD_REQUEST
                )
    def retrieve(self, request, pk=None):
        """Handle updating an object"""
        return Response({'method':'PUT'})
    def update(self, request, pk=None):
        """Handle a partial update of an object"""
        return Response({'method':'PATCH'})
    def partial_update(self, request, pk=None):
        """Handle updating part of an object"""
        return Response({'http_method': 'PATCH'})
    def delete(self, request, pk=None):
        """Delete an object"""
        return Response({'method':'DELETE'})

这是我在名为jobcard_api的应用程序中的urls.py。

from django.urls import include, path
from rest_framework.routers import DefaultRouter
from jobcard_api import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register('Jobcard-ViewSet', views.JobcardViewSet, base_name='Jobcard-ViewSet')
urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

1 个答案:

答案 0 :(得分:0)

您在视图集的list方法序列化器访问中出错。

您可以将直接的JobcardSerializer(...)实例替换为self.serializer_class,因为您已经在serializer_class = ...分配中正确分配了该值。

...

class JobcardViewSet(viewsets.ViewSet):
    serializer_class = serializers.JobcardSerializer

    def list(self, request):
        ...
        serializer = self.serializer_class(jobcard_api, many=True)