The first step, installation
pip install djangorestframework
The second step is to register the application in settings.py
INSTALLED_APPS = ['rest_framework' ]
The third step is to create a serializers.py file in the appropriate path, as follows:
The main purpose is to obtain the fields of different tables, and collect the fields in multiple tables into a large collection for easy calling
1.model specifies the serialized table
2.fields specify the required fields
3. Put a serialized instance into another serialization, then the field of this instance can also be called in the current serialization, that is, the fields in the two tables are collected together
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']
The fourth step is to import the serializers.py file in the view, call this file to put the instance to be serialized into the sequence, and then get the data through ajax
many = True: indicates queryset object, False indicates model object, default is 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())