django serializer Serializers

1, create a app03, after the settings configuration, app03 / models.py create the model and database synchronization

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, corresponding to the author table in the database which added data

 

 3, in the test file, the query author of all data tables, and serialization

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)

Execution results are as follows:

"D:\Program Files\python3.6.7\python.exe" D:/pythonWorkspace/untitled1/test_app03.py
<QuerySet [<Author: Joe>, <Author: lili>]>
[{"model": "app03.author", "pk": 1, "fields": {"name": "Joe", "email": "[email protected]"}}, {"model": "app03.author", "pk": 2, "fields": {"name": "lili", "email": "[email protected]"}}]

Process finished with exit code 0

 

Guess you like

Origin www.cnblogs.com/harryTree/p/11934658.html