django rest framework如果密钥存在,如何说创建/更新?

时间:2019-05-12 12:15:44

标签: django-rest-framework

我的序列化程序具有此创建/更新功能:

    def create(self, validated_data):
    user = models.User(
        organization_code=validated_data['organization_code'],
        username=validated_data['username'],
        personal_code=validated_data['personal_code'],
        created_by=validated_data['created_by'],
        role=validated_data['role'],
        description=self.initial_data['description'],
        start_at=self.initial_data['start_at'],
        end_at=self.initial_data['end_at']
    )
    user.set_password(validated_data['password'])
    user.save()
    return user

    def update(self, instance, validated_data):
    instance.username = validated_data.get('username', instance.username)
    instance.personal_code = validated_data.get('personal_code', instance.personal_code)
    instance.organization_code = validated_data.get('personal_code', instance.organization_code)
    instance.role = validated_data.get('role', instance.role)
    instance.published = validated_data.get('published', instance.published)
    instance.updated_by = validated_data.get('updated_by', instance.updated_by)
    instance.updated_at = validated_data.get('updated_at', instance.updated_at)
    instance.description = validated_data.get('description', instance.description)
    instance.start_at = validated_data.get('start_at', instance.start_at)
    instance.end_at = validated_data.get('end_at', instance.end_at)
    instance.is_notified_seen = validated_data.get('is_notified_seen', 0)
    instance.save()
    return instance

如果用户未填写字段,则前端不发送密钥(例如,前端的一些json没有密钥'description'),现在我检查视图,如果密钥不存在,则将密钥添加到querydict然后将其发送给序列化器,但是我不想再做了,我想在我的create函数中检查键是否存在,然后保存它,如果不执行任何操作,是否有办法解决?

0 个答案:

没有答案