django序列化器Serializers
Posted harrytree
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django序列化器Serializers相关的知识,希望对你有一定的参考价值。
1、创建一个app03, 在settings配置后, 在app03/models.py创建模型, 并同步数据库
from django.db import models # Create your models here. class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField() def __str__(self): return self.name class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) body_text = models.TextField() # pub_date = models.DateField() # mod_date = models.DateField() # authors = models.ManyToManyField(Author) number_of_comments = models.IntegerField() number_of_pingbacks = models.IntegerField() # number_of_pingbacks2 = models.IntegerField(default= None) number_of_pingbacks2 = models.IntegerField(null=True) def __str__(self): return self.headline
2、在数据库中对应的author表里面添加数据
3、在测试文件中, 查询author表的所有数据,并序列化
import os import sys from django.db import connection if __name__ == "__main__": os.environ.setdefault(‘DJANGO_SETTINGS_MODULE‘, ‘untitled1.settings‘) import django django.setup() from app03 import models from django.core import serializers authors = models.Author.objects.all() print( authors) author_list = serializers.serialize("json", authors) print(author_list)
执行结果如下:
"D:Program Filespython3.6.7python.exe" D:/pythonWorkspace/untitled1/test_app03.py <QuerySet [<Author: Joe>, <Author: lili>]> [{"model": "app03.author", "pk": 1, "fields": {"name": "Joe", "email": "joe@qq.com"}}, {"model": "app03.author", "pk": 2, "fields": {"name": "lili", "email": "lili@qq.com"}}] Process finished with exit code 0
以上是关于django序列化器Serializers的主要内容,如果未能解决你的问题,请参考以下文章