DRF⼀对多序列化和反序列化DRF⼀对多序列化和反序列化
models.py
# 商品分类
class Category(models.Model):
name = models.CharField(max_length=32)
关于教育的诗句# 商品
水浒传好句赏析class Goods(models.Model):
name = models.CharField(max_length=32)
price = models.DecimalField(max_digits=9,decimal_places=2)
阿拉蕾漫画cate = models.ForeignKey(to='Category',on_delete=models.CASCADE)
urls.py
from django.urls import path,include
专心致志的近义词from . import views
urlpatterns = [
path('goods/',views.GoodsView.as_view()),
]
ralizers.py
# 序列化
class GoodsSerializer(rializers.ModelSerializer):
# 如果想查出分类名称 CharField(source='<;本model中的外键>.<;外键指向的model的相应属性>') cate_name = rializers.CharField(source='cate.name')
class Meta:
model=Goods
fields = ('cate_name','name','price')
# 反序列化
class GoodsUnSerializer(rializers.Serializer):
name = rializers.CharField(max_length=32)
price = rializers.DecimalField(max_digits=9,decimal_places=2)
cate = rializers.IntegerField()
# 添加
def create(lf, data):
电脑任务栏在哪return ate(
cate_id = data.pop('cate'),
**data
)香港是什么时候回归祖国的
# 编辑
def update(lf,instance,data):
return instance.update(
cate_id = data.pop('cate'),
**data
)
views.py
007小游戏class GoodsView(APIView):
# 查询
def get(lf,request):
goods = models.Goods.objects.all()
gs = GoodsSerializer(goods,many=True)
美丽的春天图画
return Respon(gs.data)
# 添加
def post(lf,request):
dic = {"name":"⾦丝猴","price":132,'cate':3}
gs = GoodsUnSerializer(data=dic)
if gs.is_valid():
gs.save()
return HttpRespon('ok')
return HttpRespon('error')
# 更新
def put(lf,request):
obj = models.Goods.objects.filter(id=1)
dic = {"name":"⾦丝猴123","price":234,'cate':2} gs = GoodsUnSerializer(obj,data=dic)
if gs.is_valid():
gs.save()
return HttpRespon('put-ok')
return HttpRespon('put-error')