>> 按照官網建立prject + app數據庫
Part 1. 序列化:
(把數據庫數據轉化成特定格式json, 我的理解)django
採用原生的序列化方法:json
def publisher_list(request): queryset = Publisher.objects.all() data = [] # [方法一] user self to convert for i in queryset: p_tmp = { 'name': i.name, 'address': i.address } data.append(p_tmp) # [方法二] use django form, 可是不少 from django.froms.models import model_to_dict for i in queryset: data.append(model_to_dict(i)) import json return HttpResponse(json.dumps(data), content_type="application/json") # [方法三] use django 自帶的序列化 from django.core import serializers data = serializers.serialize("json", queryset) return HttpResponse(data, content_type="application.json")
採用django-rest-framework 序列化:app
# create file "serializers" in <app> from rest_framework import serializers from helloworld.models import Publisher class PublisherSerializer(serializers.Serializer): # 類名:表名+"Serializer" id = serializers.IntegerField(read_only=True) name = serializers.CharField(max_length=32) address = serializers.CharField(max_length=128) def create(self, validated_data): ## 從新定義 create # validated_data is dict return Publisher.objects.create(**validated_data) def update(self, instance, validated_data): ## 從新定義 update instance.name = validated_data.get("name", instance.name) instance.address = validated_data.get("address", instance.address) instance.save() return instance
from rest_framework import serializers from helloworld.models import Publisher # class PublisherSerializer(serializers.Serializer): # id = serializers.IntegerField(read_only=True) # name = serializers.CharField(max_length=32) # address = serializers.CharField(max_length=128) # # def create(self, validated_data): # # validated_data is dict # return Publisher.objects.create(**validated_data) # # def update(self, instance, validated_data): # instance.name = validated_data.get("name", instance.name) # instance.address = validated_data.get("address", instance.address) # instance.save() # return instance class PublisherSerializer(serializers.ModelSerializer): class Meta: model = Publisher fields = ( "id", "name", "address" )
使用方法:ide
# 從 DB >> json from <app>.models import Publisher form <app>.serializers import PublisherSerializer p1 = Publiser.objects.first() s1 = PublisherSerializer(p1) s1.data # Out[6]: {'id': 1, 'name': 'AAA', 'address': '3-103'} #-------------------------------------- # 從json >> DB (create) from <app>.models import Publisher form <app>.serializers import PublisherSerializer p2 = {'name': 'ZZZ', 'address': '18-103'} s2 = PublisherSerializer(data=p2) # s2.is_valid() Out[4]: True # s2.validated_data Out[5]: OrderedDict([('name', 'ZZZ'), ('address', '18-103')]) # s2.save() Out[6]: <Publisher: ZZZ>
def publisher_list(request): queryset = Publisher.objects.all() from helloworld.serializers import PublisherSerializer s = PublisherSerializer(queryset, many=True) # s.data >> 大列表, 用戶返回。 import json return HttpResponse(json.dumps(s.data), content_type="application/json")