Django自定义序列化数据

  • 模型使用系统模型

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    from __future__ import unicode_literals

    from django.db import models
    from django.contrib.auth.models import User

    class Category(models.Model):
    name = models.CharField(verbose_name=u'名称', max_length=50)
    created_at = models.DateTimeField(auto_now_add=True)
    update_at = models.DateTimeField(auto_now=True)

    def __str__(self):
    return self.name

    class Meta:
    verbose_name = '类目'
    verbose_name_plural = '类目*'


    class Blog(models.Model):
    title = models.CharField(verbose_name=u'标题', max_length=50)
    content = models.TextField(verbose_name=u'文章内容', )
    created_at = models.DateTimeField(auto_now_add=True)
    update_at = models.DateTimeField(auto_now=True)
    user = models.ForeignKey(User, verbose_name='用户', default=1)
    category = models.ForeignKey(Category, verbose_name='类目', default=1)

    def __str__(self):
    return self.title

    class Meta:
    verbose_name = '文章'
    verbose_name_plural = '文章*'
  • view中返回Json格式数据

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    from django.http import HttpResponse
    import json
    from .models import *
    from datetime import date
    from datetime import datetime

    # 时间类型需要重写
    class CJsonEncoder(json.JSONEncoder):

    def default(self, obj):
    if isinstance(obj, datetime):
    return obj.strftime('%Y-%m-%d %H:%M:%S')
    elif isinstance(obj, date):
    return obj.strftime('%Y-%m-%d')
    else:
    return json.JSONEncoder.default(self, obj)

    def get_blog(request):
    blogs = Blog.objects.all().values('id', 'title', 'content', 'created_at', 'update_at', 'category__name', 'category') # 属性关联可以用两个'_'来获取其属性
    lists = json.dumps(list(blogs), cls=CJsonEncoder)
    return HttpResponse(lists, content_type="application/json")


    def get_category(request):
    categorys = Category.objects.all().values('id', 'name', 'created_at', 'update_at')
    lists = json.dumps(list(categorys), cls=CJsonEncoder)
    return HttpResponse(lists, content_type="application/json")
本文总阅读量