django项目序列化serializers

第一步,安装

pip install djangorestframework

第二步,在settings.py里去注册应用

INSTALLED_APPS = [‘rest_framework‘
]

第三步,在合适的路径下创建一个serializers.py文件,内容如下:

主要目的是获取不同表的字段,将多个表中的字段集中为一个大的集合,方便调用

1.model指定序列化的表

2.fields指定需要的字段

3.将一个序列化的实例放入到另一个序列化里,那么在这个当前序列化里也可以调用这个实例的字段,也就是把2个表中的字段集合到了一起

from rest_framework import serializers
from .models import News,NewsCategory,Comment
from apps.xfzauth.serializers import UserSerializer

class NewsCategorySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = NewsCategory
        fields = [‘id‘,‘name‘]


class NewsSerializer(serializers.HyperlinkedModelSerializer):
    category = NewsCategorySerializer()
    author = UserSerializer()
    class Meta:
        model = News
        fields = [‘id‘,‘title‘,‘desc‘,‘thumbnail‘,‘category‘,‘author‘,‘pub_time‘]


class CommentSerializer(serializers.HyperlinkedModelSerializer):
    author = UserSerializer()
    class Meta:
        model = Comment
        fields = [‘id‘,‘content‘,‘author‘,‘pub_time‘]

第四步,在视图中导入serializers.py文件,调用此文件把要序列化的实例放进去实现序列,然后在通过ajax把数据得到

many=True:表示queryset对象,False表示为model对象,默认为False

def news_comment(request):
    commentform = CommentForm(request.POST)
    print(request.POST)
    print(commentform.is_valid())
    if commentform.is_valid():
        content = commentform.cleaned_data.get(‘content‘)
        news_id = commentform.cleaned_data.get(‘news_id‘)
        news = News.objects.get(pk=news_id)
        comment = Comment.objects.create(content=content,news=news,author=request.user)
        serializer = CommentSerializer(comment,many=True)
        return restful.result(data=serializer.data)
    else:
        return restful.params_error(message=commentform.get_errors())