serializer只作一件事情,json化model對象,因此這一部分至關簡單前端
Django REST framework的各類技巧【目錄索引】數據庫
全部的代碼都是在下面的兩個版原本作的django
django==1.8.8 djangorestframework==3.2.5
首先是官方文檔json
拿基本的user,group爲例子api
首先一個關聯的modelide
class UserProfile(TimeStampedModel): user = models.OneToOneField(User, unique=True, db_index=True, related_name='profile') name = models.CharField(blank=True, max_length=255, db_index=True) phone = models.CharField(default='', blank=True, max_length=64) nickname = models.CharField(blank=True, null=True, max_length=255, db_index=True) avatar = models.URLField(blank=True, max_length=255, default='') is_cms_user = models.BooleanField(default=False, db_index=True) is_cms_active = models.BooleanField(default=False, db_index=True) class Meta: # pylint: disable=missing-docstring db_table = "auth_userprofile" def __unicode__(self): return self.name
User對應的serializerui
class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('id', 'name') class UserSerializer(serializers.ModelSerializer): groups = GroupSerializer(many=True) phone = serializers.CharField(source='profile.phone', read_only=True) name = serializers.CharField(source='profile.name', read_only=True) menus = serializers.SerializerMethodField() is_active = serializers.BooleanField(source='profile.is_cms_active') def get_menus(self, user): return get_menus(user) class Meta: model = User fields = ('id', 'username', 'name', 'email', 'phone', 'groups', 'menus', 'is_active')
一個請求的response.net
{ "id": 2, "username": "duoduo3369", "name": "", "email": "", "phone": "", "groups": [ { "id": 1, "name": "sysadmin" }, { "id": 17, "name": "大學2" } ], "menus": [ { "menu": [ { "menu": [], "codename": "information.announcement", "name": "通知公告", "order": 1 }, { "menu": [], "codename": "information.examinfo", "name": "考試信息", "order": 2 } ] } ], "is_active": false }
serializer的邏輯很簡單,想到複雜的東西再說。Donerest