学习了drf 的教程后,自己摸索和修改了一些关于模型外键关联的使用 一. 创建一个外键关联的模型类
from django.db import models
""" 一对多 等关系, 把 on_deelte 放在多的方向 """
class UserType(models.Model):
caption = models.CharField(max_length=120)
class UserInfo(models.Model):
user_type = models.ForeignKey(UserType, on_delete=models.CASCADE, related_name="Type")
username = models.CharField(max_length=100)
age = models.IntegerField()
二. 创建两个相对应的序列化类
from rest_framework import serializers
from .models import UserInfo, UserType
class TypeSerializer(serializers.ModelSerializer):
class Meta:
model = UserType
exclude = ['id']
class InfoSerializer(serializers.ModelSerializer):
user_type = TypeSerializer()
class Meta:
model = UserInfo
fields = ["age", "username", "user_type"]
"""嵌套模型类 ,重写create方法 """
def create(self, validated_data):
"""
先创建主表,再创建次表
"""
type = validated_data.pop("user_type")
Ftype = type["caption"]
otype = UserType.objects.filter(caption=Ftype)
if otype.exists() == False:
c1 = UserType.objects.create(**type)
else:
c1 = otype[0]
c2 = UserInfo.objects.create(user_type=c1, **validated_data)
return c2
def update(self, instance, validated_data):
"""
重写update方法
"""
uType_data = validated_data.pop("user_type")
tyobjcet = UserType.objects.filter(caption = uType_data.get("caption"))
if tyobjcet.exists == False:
type_object = instance.user_type
instance.age = validated_data.get("age", instance.age)
instance.username = validated_data.get("username", instance.username)
instance.save()
type_object.caption = uType_data.get("caption", type_object.caption)
type_object.save()
else:
instance.user_type = tyobjcet[0]
type_object = instance.user_type
instance.age = validated_data.get("age", instance.age)
instance.username = validated_data.get("username", instance.username)
instance.save()
return instance
此处主要是在 modelSerilaizer下重写了 create() 与 Update()方法; 实列 在shell中使用create方法
from UserType.serializer import InfoSerializer,TypeSerializer
>>> data = {"age":26, "username":"testcreate","user_type":{"caption": "None"}}
>>> ob = InfoSerializer(data=data)
>>> ob.is_valid()
True
>>> ob.save()
<UserInfo: UserInfo object (5)>
>>> ob.data
{'age': 26, 'username': 'testcreate', 'user_type': OrderedDict([('caption', 'None')])}
>>>
在shell中的使用update方法
>>> from UserType.serializer import InfoSerializer,TypeSerializer
>>> from UserType.models import UserInfo, UserType
>>> data = {"age":26, "username":"testyjx+1","user_type":{"caption": "female"}}
>>> ob = UserInfo.objects.filter(pk=1)
>>> ob[0]
<UserInfo: UserInfo object (1)>
>>> da = InfoSerializer(ob[0], data=data)
>>> da.is_valid()
True
>>> da.save()
<UserInfo: UserInfo object (1)>
>>> da.data
{'age': 26, 'username': 'testyjx+1', 'user_type': OrderedDict([('caption', 'female')])}
总结: 主要官方drf 教程中只有简单的使用,在API指南的使用也是比较单一的,create()与update()可以自定义diy;官方不支持自动处理多嵌套处理;有第三方库DRF Writable Nested支持;后续再写一篇关于DRF Writable Nested的使用
|