DjangoRestFramework:AttributeError:'str'对象没有属性'_meta'

时间:2019-07-18 14:12:28

标签: python django rest django-rest-framework backend

我跟踪了此错误,发现serializer.data引起了问题。我在其他Django应用程序中使用了类似的代码,它们运行得很好。

models.py

from django.db import models

class Category(models.Model):
    name=models.CharField(max_length=30)
    def __str__(self):
        return self.name

class Subcategory(models.Model):
    category=models.ForeignKey(Category,on_delete=models.CASCADE)
    name=models.CharField(max_length=30)
    def __str__(self):
        return self.name

class Products(models.Model):
    Subcategory=models.ForeignKey(Subcategory,on_delete=models.CASCADE)
    name=models.CharField(max_length=30)
    def __str__(self):
        return self.name    

serializers.py

from rest_framework import serializers
from .models import Category,Subcategory,Products

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model='Category'
        fields='__all__'

class SubcategorySerializer(serializers.ModelSerializer):
    class Meta:
        model='Subcategory'
        fields='__all__'

class ProductsSerializer(serializers.ModelSerializer):
    class Meta:
        model='Products'
        fields='__all__'

views.py

    def post(self,request):
        action=request.query_params['action']
        if action=='add':
            category_name=request.query_params['category_name']
            category=Category(name=category_name)
            category.save()
            serializer=CategorySerializer(Category.objects.filter(name=category),many=True)
            return JsonResponse({"category details":serializer.data})

我根据此错误浏览了StackOverflow上的所有帖子,但没有一个可以帮助我解决它。

1 个答案:

答案 0 :(得分:2)

model字段应引用模型类,而不是带有类名的字符串(文字),例如:

from rest_framework import serializers
from .models import Category, Subcategory, Products

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = '__all__'

class SubcategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Subcategory
        fields = '__all__'

class ProductsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Products
        fields = '__all__'

这里model = Category,不是 model = 'Category' 。其他串行器也一样。

您的post视图中的逻辑并不完全正确,您可能想对category_name进行过滤:

    def post(self,request):
        action=request.query_params['action']
        if action=='add':
            category_name=request.query_params['category_name']
            category=Category(name=category_name)
            category.save()
            serializer=CategorySerializer(Category.objects.filter(name=category_name),many=True)
            return JsonResponse({"category details":serializer.data})
  

注意:模型通常使用单个名称,因此使用Product而不是Products