普通drf序列化
class Students(models.Model):
name = models.CharField(max_length=32)
age = models.IntegerField()
gender = models.CharField(max_length=8)
def __str__(self):
return 'Student: %s' % self.name
from rest_framework import serializers
class StudentSerializer(serializers.Serializer):
id = serializers.IntegerField()
stu_name = serializers.CharField(source='name')
age = serializers.IntegerField()
gender = serializers.CharField()
from app import models
from app.my_serializer import StudentSerializer
class Students(APIView):
def get(self, request, *args, **kwargs):
stus = models.Students.objects.all()
stu_ser = StudentSerializer(stus, many=True)
print(stus)
return Response({
'status': 0,
'msg': 'ok',
'results': stu_ser.data
})
from app import views
urlpatterns = [
url(r'^students/', views.Students.as_view()),
]
orm无关联连表操作
class User(models.Model):
user = models.CharField(max_length=32)
pwd = models.CharField(max_length=32)
user_detail = models.OneToOneField(to='UserDetail', null=True, on_delete=models.SET_NULL, db_constraint=False)
class UserDetail(models.Model):
phone_num = models.CharField(max_length=11)
info = models.TextField()
from app import models
def test(request):
user = models.User.objects.first()
return HttpResponse(user.user_detail.phone_num)
函数作为模型对象序列化
# models.py
class User(models.Model):
user = models.CharField(max_length=32)
pwd = models.CharField(max_length=32)
user_detail = models.OneToOneField(to='UserDetail', null=True, on_delete=models.SET_NULL, db_constraint=False)
# 在model中产生的全局空间名字,都可以被序列化
def account(self):
return self.user + ":" + self.pwd
class UserDetail(models.Model):
phone_num = models.CharField(max_length=11)
info = models.TextField()
两种嵌套的序列化方式(重要)
序列化方式1
class UserJson(serializers.Serializer):
name = serializers.CharField(source='user')
password = serializers.CharField(source='pwd')
account = serializers.CharField()
detail = serializers.SerializerMethodField()
def get_detail(self, obj):
phone_num = obj.user_detail.phone_num
info = obj.user_detail.info
return {'phone': phone_num, 'info': info}
序列化方式2
class UserDetailJson(serializers.Serializer):
phone_num = serializers.CharField()
info = serializers.CharField()
class UserJson(serializers.Serializer):
name = serializers.CharField(source='user')
password = serializers.CharField(source='pwd')
account = serializers.CharField()
detail = serializers.SerializerMethodField()
def get_detail(self, obj):
detail_obj = obj.user_detail
detail_data = UserDetailJson(detail_obj).data
return detail_data
基于Model的序列化
class Book(models.Model):
name = models.CharField(max_length=20)
price = models.DecimalField(max_digits=5, decimal_places=2)
author = models.ManyToManyField(to='Author', db_constraint=False)
class Author(models.Model):
name = models.CharField(max_length=20)
author_detail = models.OneToOneField(to='AuthorDetail', on_delete=models.SET_NULL, null=True, db_constraint=False)
class AuthorDetail(models.Model):
age = models.IntegerField()
telephone = models.BigIntegerField()
"""
1) 用Meta的model来绑定序列化的类
2) fields = '__all__': 序列化所有字段
3) fields = ['字段1', ..., '字段2']:指定序列化的字段
4) exclude = ['字段1', ..., '字段2']:排除序列化的字段
5) depth = 1:跨表的深度
"""
from app import models
class AuthorDetailJson(serializers.ModelSerializer):
class Meta:
model = models.AuthorDetail
exclude = ['id']
class AuthorJson(serializers.ModelSerializer):
class Meta:
model = models.Author
exclude = ['id']
detail = serializers.SerializerMethodField()
def get_detail(self, obj):
detail_data = AuthorDetailJson(obj.author_detail).data
return detail_data
class BookJson(serializers.ModelSerializer):
class Meta:
model = models.Book
fields = '__all__'
authors = serializers.SerializerMethodField()
def get_authors(self, obj):
author_list = obj.author.all()
author_data = AuthorJson(author_list, many=True).data
return author_data
class Books(APIView):
def get(self, request):
book_list = models.Book.objects.all()
book_data = objson.BookJson(book_list, many=True).data
return Response({
'status': 0,
'msg': 'ok',
'results': book_data
})
url(r'^books/', views.Books.as_view()),