django用serializers.ModelSerializer方式序列化
1.在上一篇的基础上,在users/Serializer.py中,写book的ModelSerializer序列化类:
class BookModelSerializer(serializers.ModelSerializer):
class Meta():
model=Book
fields="__all__"
如果不全都序列化,只需要修改fields=(‘字段’)
2.BookModelSerializer的API视图类:
class BookAPIView2(APIView):
def get(self,request,format=None):
APIKey = self.request.query_params.get('apikey', 0)
developer = UserProfile.objects.filter(APIKey=APIKey).first()
if developer:
balance = developer.money
if balance > 0:
isbn = self.request.query_params.get('isbn', 0)
books = Book.objects.filter(isbn=int(isbn))
books_serializer = BookModelSerializer(books, many=True)
developer.money -= 1
developer.save()
return Response(books_serializer.data)
else:
return Response('兄弟,又到需要充钱的时候!')
else:
return Response('查无此人啊!')
3.配置urls.py