【发布时间】:2020-06-30 18:34:54
【问题描述】:
我想通过函数update()更新一个实例,下面是类CardSerializer:
class CardSerializer(serializers.ModelSerializer):
image = serializers.CharField(read_only=True)
class Meta:
model = Card
fields = ('id', 'template', 'data', 'MD5', 'image_md5',
'image', 'target_url', 'title', 'description',
'created', 'updated', 'createdBy')
read_only_fields = ['MD5', 'image_md5', 'image', 'createdBy']
def update(self, instance, validated_data):
# TODO Bug Fix
new_ins = Card(**instance.data.update(validated_data))
md5 = new_ins.gen_md5()
lookup = Card.objects.filter(MD5=md5).first()
if lookup:
return lookup
return super(CardSerializer, self).update(instance, validated_data)
目前我在一个卡片实例 (id=206) http://127.0.0.1:8000/api/Card/206/ 中使用 patch 和正文 {"title": "asd"} ,但会引发错误{模板:没有此字段}。然后我 degug,发现函数 update(self, instance, valid_data) 无法在行中生成新实例 (new_ins)
new_ins = Card(**instance.data.update(validated_data))
调试控制台中的 arg validated_data 是
>validated_data
{'title': 'asd'}
'title':'asd'
__len__:1
实例是类对象 Card() :
data:{'address': '123 Sydney St, Sydn... NSW 2000',
'avatar': 'https://cn.meetkol...._real.jpg',
'cover': 'https://cn.tdintell...Group.jpg',
'desc': 'vvvvbbbbbbxxxxxx jush oaighijjjoh',
'mail': 'zhujia@email.com',
'phone': '(61)0 410 888 888',
'qr': 'https://zhujia.com....ge/qr.png',
'title': 'new building',
'user': 'Martin'
}
MD5:'ae853b247d8510f06a9741e74b7851c3'
description:''
pk:206
template:<CardTemplate: 7 | property_share_long | v1 long>
template_id:7
title:''
updated:datetime.datetime(2020, 6, 30, 1, 35, 32, 871820, tzinfo=<UTC>)
'createdBy':<User: stevenqin>
【问题讨论】:
-
我想知道如何用多个字段更新这个实例
标签: python django django-rest-framework