django的rest-framework是django很贴心的为我们准备的一个实例化app
https://www.django-rest-framework.org/
安装这个app
pip install djangorestframework
安装好之后需要我们在项目的setting里面注册这个app
INSTALLED_APPS = [ ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘app01.apps.App01Config‘, "rest_framework", ]
现在我们就可以使用他的功能了,在使用之前我们可以先来看下我们之前是怎么来序列化的,先导入一些测试的数据:
from django.db import models # Create your models here. class Book(models.Model): title=models.CharField(max_length=32) price=models.IntegerField() pub_date=models.DateField() publish=models.ForeignKey("Publish") authors=models.ManyToManyField("Author") def __str__(self): return self.title class Publish(models.Model): name=models.CharField(max_length=32) email=models.EmailField() def __str__(self): return self.name class Author(models.Model): name=models.CharField(max_length=32) age=models.IntegerField() def __str__(self): return self.name
首先我们看下我们可以使用的第一种方式:
from django.views import View from app01.models import * import json class PublishView(View): def get(self,request): # 方式一 # publish_list = list(Publish.objects.all().values("id","name")) # 或者也可以这样 publish_list = Publish.objects.all() tem = [] for obj in publish_list: tem.append({ "id":obj.pk, "name":obj.name }) # return HttpResponse(json.dumps(publish_list)) return HttpResponse(json.dumps(tem))
原文地址:https://www.cnblogs.com/cuilinpu/p/10356778.html
时间: 2024-11-15 22:32:40