zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    算法:字符串处理
    写点什么好呢3?昨日的宝贝成了今日的负担!
    商业研究(22):股权投资,大有可为?
    商业研究(22):股权投资,大有可为?
    .Net Task常见问题
    使用OKHttp模拟登陆知乎,兼谈OKHttp中Cookie的使用!
    Android开发——Android 6.0权限管理机制详解
    创业有套路
    创业有套路
    半分钟内能看透问题本质的人是如何思考的?
  • 原文地址:https://www.cnblogs.com/harryTree/p/11934658.html
Copyright © 2011-2022 走看看