コード例 #1
0
    def update(self, instance, validated_data):
        raise_errors_on_nested_writes('update', self, validated_data)
        info = model_meta.get_field_info(instance)
        profile = instance.userprofile
        picture = instance.userprofile.picture
        p_info = model_meta.get_field_info(profile)
        pic_info = model_meta.get_field_info(picture)

        for attr, value in validated_data.items():
            if attr == 'userprofile':
                for attr2, value2 in value.items():
                    if attr2 == 'picture':
                        for attr3, value3 in value2.items():
                            setattr(picture, attr3, value3)
                    else:
                        setattr(profile, attr2, value2)

            elif attr in info.relations and info.relations[attr].to_many:
                field = getattr(instance, attr)
                field.set(value)
            else:
                setattr(instance, attr, value)
        instance.save()
        picture.save()
        profile.save()

        return instance
コード例 #2
0
 def create(self, validated_data: Dict, *args: Any,
            **kwargs: Any) -> Organization:
     serializers.raise_errors_on_nested_writes("create", self,
                                               validated_data)
     organization, _, _ = Organization.objects.bootstrap(
         self.context["request"].user, **validated_data)
     return organization
コード例 #3
0
    def create(self, validated_data):
        raise_errors_on_nested_writes('create', self, validated_data)
        if self.user and self.user.id:
            validated_data['user'] = self.user
        try:
            instance = Investment.objects.create(**validated_data)
        except TypeError:
            tb = traceback.format_exc()
            msg = (
                'Got a `TypeError` when calling `%s.objects.create()`. '
                'This may be because you have a writable field on the '
                'serializer class that is not a valid argument to '
                '`%s.objects.create()`. You may need to make the field '
                'read-only, or override the %s.create() method to handle '
                'this correctly.\nOriginal exception was:\n %s' %
                (
                    Investment.__name__,
                    Investment.__name__,
                    self.__class__.__name__,
                    tb
                )
            )
            raise TypeError(msg)

        return instance
コード例 #4
0
ファイル: serializers.py プロジェクト: lautarovc/theam-test
    def update(self, instance, validated_data):
        # Assigns current user to the lastUpdatedBy attribute
        validated_data['lastUpdatedBy'] = self.context['request'].user

        serializers.raise_errors_on_nested_writes('update', self,
                                                  validated_data)
        info = serializers.model_meta.get_field_info(instance)

        old_instance = Customer.objects.get(pk=instance.id)

        # Simply set each attribute on the instance, and then save it.
        # Note that unlike `.create()` we don't need to treat many-to-many
        # relationships as being a special case. During updates we already
        # have an instance pk for the relationships to be associated with.
        m2m_fields = []
        for attr, value in validated_data.items():
            if attr in info.relations and info.relations[attr].to_many:
                m2m_fields.append((attr, value))
            else:
                setattr(instance, attr, value)
        instance.save()

        # This is done because editing the id creates another instance, NOT recommended
        # for more complex models where customer is a foreign key to another table
        if (old_instance.id != instance.id):
            old_instance.delete()

        # Note that many-to-many fields are set after updating instance.
        # Setting m2m fields triggers signals which could potentially change
        # updated instance and we do not want it to collide with .update()
        for attr, value in m2m_fields:
            field = getattr(instance, attr)
            field.set(value)

        return instance
コード例 #5
0
ファイル: serializers.py プロジェクト: nie000/mylinuxlearn
    def update(self, instance: Employee, validated_data):
        raise_errors_on_nested_writes('update', self, validated_data)
        info = model_meta.get_field_info(instance)

        # Simply set each attribute on the instance, and then save it.
        # Note that unlike `.create()` we don't need to treat many-to-many
        # relationships as being a special case. During updates we already
        # have an instance pk for the relationships to be associated with.
        m2m_fields = []
        for attr, value in validated_data.items():
            if attr in info.relations and info.relations[attr].to_many:
                m2m_fields.append((attr, value))
            else:
                setattr(instance, attr, value)
                # instance.title='工程师'
                # setattr(instance,'title','工程师')
        with transaction.atomic():
            instance.save()
            instance.salary.basesalary = validated_data.get('basesalary')
            instance.salary.titlesalary = validated_data.get('titlesalary')
            instance.salary.save()
        # Note that many-to-many fields are set after updating instance.
        # Setting m2m fields triggers signals which could potentially change
        # updated instance and we do not want it to collide with .update()
        for attr, value in m2m_fields:
            field = getattr(instance, attr)
            field.set(value)

        return instance
コード例 #6
0
    def create(self, validated_data):
        #raise Exception(validated_data)
        serializers.raise_errors_on_nested_writes('create', self, validated_data)

        ModelClass = self.Meta.model
        info = model_meta.get_field_info(ModelClass)
        many_to_many = {}
        for field_name, relation_info in info.relations.items():
            if relation_info.to_many and (field_name in validated_data):
                many_to_many[field_name] = validated_data.pop(field_name)

        try:
            instance = ModelClass(**validated_data)
        except TypeError as exc:
            msg = (
                'Got a `TypeError` when calling `%s.objects.create()`. '
                'This may be because you have a writable field on the '
                'serializer class that is not a valid argument to '
                '`%s.objects.create()`. You may need to make the field '
                'read-only, or override the %s.create() method to handle '
                'this correctly.\nOriginal exception text was: %s.' %
                (
                    ModelClass.__name__,
                    ModelClass.__name__,
                    self.__class__.__name__,
                    exc
                )
            )
            raise TypeError(msg)
        if many_to_many:
            for field_name, value in many_to_many.items():
                setattr(instance, field_name, value)
        return instance
コード例 #7
0
ファイル: serializers.py プロジェクト: hellojerry/buddy
    def update(self, instance, validated_data):
        serializers.raise_errors_on_nested_writes('update',
                                                  self, validated_data)
        provided_time = validated_data['provided_time']
        weekday = validated_data['day_of_week']
        try:
            day = available[weekday]
        except KeyError:
            print("That's not a valid day.")
        today = datetime.datetime.now(pytz.UTC)
        schedule_date = next_weekday(today, day)
        schedule_time = datetime.datetime.strptime(provided_time, '%H:%M')
        hour = schedule_time.hour
        minute = schedule_time.minute
        final_time = schedule_date.replace(hour=hour, minute=minute,
                                           second=0, microsecond=0)

        local_tz = pytz.timezone(validated_data['user'].time_zone)
        offset_amt = local_tz.utcoffset(datetime.datetime.now())
        final_time -= offset_amt
        validated_data['time'] = final_time
        validated_data.pop('provided_time', None)
        validated_data.pop('day_of_week', None)
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()

        return instance
コード例 #8
0
ファイル: serializers.py プロジェクト: SergioKK/sell_api
    def create(self, validated_data):
        raise_errors_on_nested_writes('create', self, validated_data)

        ModelClass = self.Meta.model
        info = model_meta.get_field_info(ModelClass)
        many_to_many = {}
        for field_name, relation_info in info.relations.items():
            if relation_info.to_many and (field_name in validated_data):
                many_to_many[field_name] = validated_data.pop(field_name)

        try:
            instance = ModelClass._default_manager.create_user(
                **validated_data)
        except TypeError:
            tb = traceback.format_exc()
            msg = ('Got a `TypeError` when calling `%s.%s.create()`. '
                   'This may be because you have a writable field on the '
                   'serializer class that is not a valid argument to '
                   '`%s.%s.create()`. You may need to make the field '
                   'read-only, or override the %s.create() method to handle '
                   'this correctly.\nOriginal exception was:\n %s' %
                   (ModelClass.__name__, ModelClass._default_manager.name,
                    ModelClass.__name__, ModelClass._default_manager.name,
                    self.__class__.__name__, tb))
            raise TypeError(msg)

        # Save many-to-many relationships after the instance is created.
        if many_to_many:
            for field_name, value in many_to_many.items():
                field = getattr(instance, field_name)
                field.set(value)

        return instance
コード例 #9
0
    def create(self, validated_data):

        raise_errors_on_nested_writes('create', self, validated_data)

        ModelClass = self.Meta.model

        # Remove many-to-many relationships from validated_data.
        # They are not valid arguments to the default `.create()` method,
        # as they require that the instance has already been saved.
        info = model_meta.get_field_info(ModelClass)
        many_to_many = {}
        for field_name, relation_info in info.relations.items():
            if relation_info.to_many and (field_name in validated_data):
                many_to_many[field_name] = validated_data.pop(field_name)

        try:
            instance = ModelClass._default_manager.create_user(
                **validated_data)
        except TypeError:
            tb = traceback.format_exc()
            msg = ((ModelClass.__name__, ModelClass._default_manager.name,
                    ModelClass.__name__, ModelClass._default_manager.name,
                    self.__class__.__name__, tb))
            raise TypeError(msg)

        # Save many-to-many relationships after the instance is created.
        if many_to_many:
            for field_name, value in many_to_many.items():
                field = getattr(instance, field_name)
                field.set(value)

        return instance
コード例 #10
0
    def update(self, instance, validated_data):
        if validated_data["order_pay"] == 3:
            # 待退款
            time_obj = Time.objects.filter(
                time_id=validated_data["order_timeid"].time_id).first()
            time_obj.time_surplus += 1
            time_obj.save()

        raise_errors_on_nested_writes('update', self, validated_data)
        info = model_meta.get_field_info(instance)

        m2m_fields = []
        for attr, value in validated_data.items():
            if attr in info.relations and info.relations[attr].to_many:
                m2m_fields.append((attr, value))
            else:
                setattr(instance, attr, value)

        instance.save()

        for attr, value in m2m_fields:
            field = getattr(instance, attr)
            field.set(value)

        return instance
コード例 #11
0
    def update(self, instance, validated_data):
        raise_errors_on_nested_writes('update', self, validated_data)

        password = validated_data.get('password')
        print('hello')

        if password:
            instance.password = password
            instance.user.set_password(password)
            print('password', instance.password, 'user password', instance.user.password)

        instance.user.save()
        instance.save()
        return instance
        #
        # password = validated_data.get('password')
        # print('password ', password)
        #
        # for attr, value in validated_data.items():
        #     setattr(instance, attr, value)
        #
        # instance.save()
        #
        # if password:
        #     print('password111 ', password)
        #
        #     instance.password = password
        #     instance.save()
        #
        # # instance.user.save()
        #
        # return instance
コード例 #12
0
ファイル: serializers.py プロジェクト: richpolis/AlsEvaTec
    def update(self, instance, validated_data):
        raise_errors_on_nested_writes('update', self, validated_data)
        info = model_meta.get_field_info(instance)
        if 'name' in validated_data:
            model = Album
            name = validated_data['name']
            validated_data['slug'] = slug_generator(name, model)
        from_zone = pytz.timezone(TIME_ZONE)
        if not 'created_at' in validated_data:
            validated_data['created_at'] = instance.created_at
        else:
            validated_data['created_at'] = validated_data[
                'created_at'].astimezone(from_zone)
        if not 'updated_at' in validated_data:
            validated_data['updated_at'] = timezone.now()
        else:
            validated_data['updated_at'] = validated_data[
                'updated_at'].astimezone(from_zone)
        for attr, value in validated_data.items():
            if attr in info.relations and info.relations[attr].to_many:
                field = getattr(instance, attr)
                field.set(value)
            else:
                setattr(instance, attr, value)
        instance.save()

        return instance
コード例 #13
0
ファイル: serializers.py プロジェクト: Zarinabonu/ForceApp
    def update(self, instance, validated_data):
        raise_errors_on_nested_writes('update', self, validated_data)

        if validated_data.get('class_id_id'):
            c = validated_data.pop('class_id_id')
            cla = Class.objects.get(id=c)
            print(c)
            instance.class_id = cla
            instance.class_id.save()
        if validated_data.get('subject_id'):
            s = validated_data.pop('subject_id')
            sub = Subject.objects.get(id=s)
            instance.subject = sub
            instance.subject.save()
        if validated_data.get('teacher_id'):
            t = validated_data.pop('teacher_id')
            teach = Teacher.objects.get(id=t)
            instance.teacher = teach
            instance.teacher.save()
        if validated_data.get('quater_id'):
            q = validated_data.pop('quater_id')
            qua = Quater.objects.get(id=q)
            instance.quater = qua
            instance.quater.save()
        start_d = validated_data.get('start_date')
        instance.start_date = start_d
        finish_d = validated_data.get('finish_date')
        instance.finish_date = finish_d
        d = validated_data.get('day')
        instance.day = d

        instance.save()
        return instance
コード例 #14
0
    def create(self, validated_data):
        """Override of create method."""
        """
        We have a bit of extra checking around this in order to provide
        descriptive messages when something goes wrong, but this method is
        essentially just:
            return ExampleModel.objects.create(**validated_data)
        If there are many to many fields present on the instance then they
        cannot be set until the model is instantiated, in which case the
        implementation is like so:
            example_relationship = validated_data.pop('example_relationship')
            instance = ExampleModel.objects.create(**validated_data)
            instance.example_relationship = example_relationship
            return instance
        The default implementation also does not handle nested relationships.
        If you want to support writable nested relationships you'll need
        to write an explicit `.create()` method.
        """
        raise_errors_on_nested_writes("create", self, validated_data)

        ModelClass = self.Meta.model

        # Remove many-to-many relationships from validated_data.
        # They are not valid arguments to the default `.create()` method,
        # as they require that the instance has already been saved.
        info = model_meta.get_field_info(ModelClass)
        many_to_many = {}
        for field_name, relation_info in info.relations.items():
            if relation_info.to_many and (field_name in validated_data):
                many_to_many[field_name] = validated_data.pop(field_name)

        try:
            for request_tenant in schema_handler(
                    self.context["request"].tenant):
                instance = ModelClass._default_manager.create(
                    **validated_data, tenant=request_tenant)
        except TypeError:
            tb = traceback.format_exc()
            msg = ("Got a `TypeError` when calling `%s.%s.create()`. "
                   "This may be because you have a writable field on the "
                   "serializer class that is not a valid argument to "
                   "`%s.%s.create()`. You may need to make the field "
                   "read-only, or override the %s.create() method to handle "
                   "this correctly.\nOriginal exception was:\n %s" % (
                       ModelClass.__name__,
                       ModelClass._default_manager.name,
                       ModelClass.__name__,
                       ModelClass._default_manager.name,
                       self.__class__.__name__,
                       tb,
                   ))
            raise TypeError(msg)

        # Save many-to-many relationships after the instance is created.
        if many_to_many:
            for field_name, value in many_to_many.items():
                field = getattr(instance, field_name)
                field.set(value)

        return instance
コード例 #15
0
    def create(self, validated_data):
        raise_errors_on_nested_writes('create', self, validated_data)

        ModelClass = self.Meta.model

        try:
            user = ModelClass._default_manager.create_user(**validated_data)
        except TypeError:
            tb = traceback.format_exc()
            msg = ('Got a `TypeError` when calling `%s.%s.create()`. '
                   'This may be because you have a writable field on the '
                   'serializer class that is not a valid argument to '
                   '`%s.%s.create()`. You may need to make the field '
                   'read-only, or override the %s.create() method to handle '
                   'this correctly.\nOriginal exception was:\n %s' %
                   (ModelClass.__name__, ModelClass._default_manager.name,
                    ModelClass.__name__, ModelClass._default_manager.name,
                    self.__class__.__name__, tb))
            raise TypeError(msg)
        token = Token.objects.create(user_id=user.id)
        self.data.update({'Authorization': f'Token {token.key}'})
        self._data.update({'Authorization': f'Token {token.key}'})

        # self.validated_data.update({'Authorization': f'Token {token.key}'})
        # self.initial_data.update({'Authorization': f'Token {token.key}'})
        # self._validated_data.update({'Authorization': f'Token {token.key}'})
        return user
コード例 #16
0
ファイル: serializers.py プロジェクト: hellojerry/buddy
    def update(self, instance, validated_data):
        serializers.raise_errors_on_nested_writes('update', self,
                                                  validated_data)
        provided_time = validated_data['provided_time']
        weekday = validated_data['day_of_week']
        try:
            day = available[weekday]
        except KeyError:
            print("That's not a valid day.")
        today = datetime.datetime.now(pytz.UTC)
        schedule_date = next_weekday(today, day)
        schedule_time = datetime.datetime.strptime(provided_time, '%H:%M')
        hour = schedule_time.hour
        minute = schedule_time.minute
        final_time = schedule_date.replace(hour=hour,
                                           minute=minute,
                                           second=0,
                                           microsecond=0)

        local_tz = pytz.timezone(validated_data['user'].time_zone)
        offset_amt = local_tz.utcoffset(datetime.datetime.now())
        final_time -= offset_amt
        validated_data['time'] = final_time
        validated_data.pop('provided_time', None)
        validated_data.pop('day_of_week', None)
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()

        return instance
コード例 #17
0
ファイル: base.py プロジェクト: socketbox/studio
    def create(self, validated_data):
        # To ensure caution, require nested_writes to be explicitly allowed
        if not (hasattr(self.Meta, "nested_writes") and self.Meta.nested_writes):
            raise_errors_on_nested_writes("create", self, validated_data)

        ModelClass = self.Meta.model

        # Remove many-to-many relationships from validated_data.
        # They are not valid arguments to the default `.create()` method,
        # as they require that the instance has already been saved.
        info = model_meta.get_field_info(ModelClass)
        for field_name, relation_info in info.relations.items():
            if relation_info.to_many and (field_name in validated_data):
                raise ValueError(
                    "Many to many fields must be explicitly handled", field_name
                )
            elif not relation_info.reverse and (field_name in validated_data):
                if not isinstance(
                    validated_data[field_name], relation_info.related_model
                ):
                    # Trying to set a foreign key but do not have the object, only the key
                    validated_data[
                        relation_info.model_field.attname
                    ] = validated_data.pop(field_name)

        instance = ModelClass(**validated_data)

        if hasattr(instance, "on_create") and callable(instance.on_create):
            instance.on_create()

        if not getattr(self, "parent", False):
            instance.save()

        return instance
コード例 #18
0
    def update(self, instance, validated_data):
        print(instance, validated_data)
        raise_errors_on_nested_writes('update', self, validated_data)
        info = model_meta.get_field_info(instance)

        extra_fields, validated_data = retrieve_extra_fields(**validated_data)

        m2m_fields = []
        for attr, value in validated_data.items():
            if attr in info.relations and info.relations[attr].to_many:
                m2m_fields.append((attr, value))
            else:
                setattr(instance, attr, value)

        for attr, value in extra_fields.items():
            setattr(instance.more, attr, value)

        instance.save()
        instance.more.save()

        for attr, value in m2m_fields:
            field = getattr(instance, attr)
            field.set(value)

        return instance
コード例 #19
0
    def update(self, instance, validated_data):
        raise_errors_on_nested_writes('update', self, validated_data)
        request = self.context['request']
        u = User.objects.get(id=request.user.id)
        if u.employee.position.degree == 9:
            status_code = validated_data.pop('status')
            task = Task(**validated_data)
            task.save()

            employee_id = Employee.objects.get(id=request.user.id)

            status = Status.objects.get(code=status_code)
            t = Task_status.objects.create(status=status, task=task)
            t.editer = employee_id

            if status.code == 4:
                instance.done_date = datetime.today().date()
                print(datetime.today().date())
                t.save()
                instance.save()

        for attr, value in validated_data.items():
            setattr(instance, attr, value)

        return instance
コード例 #20
0
    def test_nested_serializer_create_and_update(self):
        class NonRelationalPersonDataSerializer(serializers.Serializer):
            occupation = serializers.CharField()

        class NonRelationalPersonSerializer(serializers.ModelSerializer):
            data = NonRelationalPersonDataSerializer()

            class Meta:
                model = NonRelationalPersonModel
                fields = ['data']

        serializer = NonRelationalPersonSerializer(
            data={'data': {
                'occupation': 'developer'
            }})
        assert serializer.is_valid()
        assert serializer.validated_data == {
            'data': {
                'occupation': 'developer'
            }
        }
        raise_errors_on_nested_writes('create', serializer,
                                      serializer.validated_data)
        raise_errors_on_nested_writes('update', serializer,
                                      serializer.validated_data)
コード例 #21
0
    def update(self, instance, validated_data):
        """
        Default `.update()` method, but with overwritten friends' m2m assignment and return object annotation
        :param instance:
        :param validated_data:
        :return:
        """
        raise_errors_on_nested_writes('update', self, validated_data)
        info = model_meta.get_field_info(instance)

        m2m_fields = []
        for attr, value in validated_data.items():
            if attr in info.relations and info.relations[attr].to_many:
                m2m_fields.append((attr, value))
            else:
                setattr(instance, attr, value)

        instance.save()

        for attr, value in m2m_fields:
            field = getattr(instance, attr)
            if attr == 'friends':
                field.set(value, through_defaults={'created_at': timezone.now()})

        return self.context['view'].get_object()
コード例 #22
0
    def update(self, instance, validated_data):
        raise_errors_on_nested_writes('update', self, validated_data)
        info = model_meta.get_field_info(instance)

        active_plan_id = validated_data.pop('active_plan', None)

        # Simply set each attribute on the instance, and then save it.
        # Note that unlike `.create()` we don't need to treat many-to-many
        # relationships as being a special case. During updates we already
        # have an instance pk for the relationships to be associated with.
        for attr, value in validated_data.items():
            if attr in info.relations and info.relations[attr].to_many:
                field = getattr(instance, attr)
                field.set(value)
            else:
                setattr(instance, attr, value)

        if active_plan_id:
            active_plan_id = active_plan_id['id']
            try :
                plan = Plan.objects.get(pk=active_plan_id)
            except:
                raise PlanDoesNotExist()
            setattr(instance, 'active_plan', plan)

        instance.save()

        return instance
コード例 #23
0
ファイル: serializers.py プロジェクト: opendp/dpcreator
    def update(self, instance, validated_data):
        """
        Override default update method to counteract race conditions.
        (See https://github.com/encode/django-rest-framework/issues/5897)
        :param instance:
        :param validated_data:
        :return:
        """
        raise_errors_on_nested_writes('update', self, validated_data)
        info = model_meta.get_field_info(instance)
        update_fields = []

        for attr, value in validated_data.items():
            update_fields.append(attr)
            if attr in info.relations and info.relations[attr].to_many:
                field = getattr(instance, attr)
                field.set(value)
            else:
                setattr(instance, attr, value)
        # if instance.variable_info and instance.epsilon \
        #         and instance.user_step == instance.DepositorSteps.STEP_0600_EPSILON_SET:
        #     instance.is_complete = True
        # else:
        #     instance.is_complete = False

        # This needs to be added to tell the save method to update the value.
        update_fields.append('is_complete')

        # Specifically for this model, we are overriding the update method with an explicit list of
        # update_fields, so we need to set the updated field manually.
        # All other models will be updated without this step due to the auto_now option from the parent class.
        instance.updated = timezone.now()
        instance.save(update_fields=update_fields)

        return instance
コード例 #24
0
    def create(self, validated_data):
        """
        We have a bit of extra checking around this in order to provide
        descriptive messages when something goes wrong, but this method is
        essentially just:

            return ExampleModel.objects.create(**validated_data)

        If there are many to many fields present on the instance then they
        cannot be set until the model is instantiated, in which case the
        implementation is like so:

            example_relationship = validated_data.pop('example_relationship')
            instance = ExampleModel.objects.create(**validated_data)
            instance.example_relationship = example_relationship
            return instance

        The default implementation also does not handle nested relationships.
        If you want to support writable nested relationships you'll need
        to write an explicit `.create()` method.
        """
        raise_errors_on_nested_writes('create', self, validated_data)

        ModelClass = self.Meta.model

        # Remove many-to-many relationships from validated_data.
        # They are not valid arguments to the default `.create()` method,
        # as they require that the instance has already been saved.
        info = model_meta.get_field_info(ModelClass)
        many_to_many = {}
        for field_name, relation_info in info.relations.items():
            if relation_info.to_many and (field_name in validated_data):
                many_to_many[field_name] = validated_data.pop(field_name)

        try:
            instance = ModelClass.objects.create(**validated_data)
        except TypeError as exc:
            msg = (
                'Got a `TypeError` when calling `%s.objects.create()`. '
                'This may be because you have a writable field on the '
                'serializer class that is not a valid argument to '
                '`%s.objects.create()`. You may need to make the field '
                'read-only, or override the %s.create() method to handle '
                'this correctly.\nOriginal exception text was: %s.' %
                (
                    ModelClass.__name__,
                    ModelClass.__name__,
                    self.__class__.__name__,
                    exc
                )
            )
            raise TypeError(msg)

        # Save many-to-many relationships after the instance is created.
        if many_to_many:
            for field_name, value in many_to_many.items():
                setattr(instance, field_name, value)

        return instance
コード例 #25
0
    def update(self, instance, validated_data):
        serializers.raise_errors_on_nested_writes('update', self,
                                                  validated_data)

        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save(using=instance.appID)
        return instance
コード例 #26
0
ファイル: serializers.py プロジェクト: varunsharma/kolibri
 def update(self, instance, validated_data):
     if 'password' in validated_data:
         serializers.raise_errors_on_nested_writes('update', self, validated_data)
         instance.set_password(validated_data['password'])
         instance.save()
         return instance
     else:
         return super(DeviceOwnerSerializer, self).update(instance, validated_data)
コード例 #27
0
    def update(self, instance, validated_data):
        serializers.raise_errors_on_nested_writes('update', self,
                                                  validated_data)
        info = model_meta.get_field_info(instance)

        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save(using=instance.person.appID)
        return instance
コード例 #28
0
 def create(self, validated_data: Dict[str, Any], **kwargs) -> Team:
     serializers.raise_errors_on_nested_writes("create", self, validated_data)
     request = self.context["request"]
     organization = self.context["view"].organization  # use the org we used to validate permissions
     with transaction.atomic():
         team = Team.objects.create_with_data(**validated_data, organization=organization)
         request.user.current_team = team
         request.user.save()
     return team
コード例 #29
0
ファイル: team.py プロジェクト: zhang1998/posthog
 def create(self, validated_data: Dict[str, Any]) -> Team:
     serializers.raise_errors_on_nested_writes("create", self, validated_data)
     request = self.context["request"]
     with transaction.atomic():
         validated_data.setdefault("completed_snippet_onboarding", True)
         team = Team.objects.create_with_data(**validated_data, organization=request.user.organization)
         request.user.current_team = team
         request.user.save()
     return team
コード例 #30
0
ファイル: group.py プロジェクト: jeongmyeonghyeon/chming
    def update(self, instance, validated_data):
        raise_errors_on_nested_writes('update', self, validated_data)

        for attr, value in validated_data.items():
            setattr(instance, attr, value)

        instance.save()

        return instance
コード例 #31
0
ファイル: serializers.py プロジェクト: KraftSoft/together
    def update(self, instance, validated_data):
        raise_errors_on_nested_writes('update', self, validated_data)

        for attr, value in validated_data.items():
            if attr in self.UPDATE_AVAILABLE_FIELDS:
                setattr(instance, attr, value)

        instance.save()

        return instance
コード例 #32
0
 def create(self, validated_data: Dict[str, Any], **kwargs) -> Team:
     serializers.raise_errors_on_nested_writes("create", self, validated_data)
     request = self.context["request"]
     organization = request.user.organization
     if organization is None:
         raise exceptions.ValidationError("You need to belong to an organization first!")
     with transaction.atomic():
         team = Team.objects.create_with_data(**validated_data, organization=organization)
         request.user.current_team = team
         request.user.save()
     return team
コード例 #33
0
    def update(self, instance, validated_data):

        raise_errors_on_nested_writes('update', self, validated_data)
        if 'password' in validated_data:
            instance.set_password(validated_data.pop('password'))
        for attr, value in validated_data.items():
            setattr(instance, attr, value)

        instance.save()

        return instance
コード例 #34
0
ファイル: serializers.py プロジェクト: hellojerry/buddy
    def update(self, instance, validated_data):

        serializers.raise_errors_on_nested_writes('update', self, validated_data)

        # Simply set each attribute on the instance, and then save it.
        # Note that unlike `.create()` we don't need to treat many-to-many
        # relationships as being a special case. During updates we already
        # have an instance pk for the relationships to be associated with.
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()
        return instance
コード例 #35
0
ファイル: serializers.py プロジェクト: Zarinabonu/ForceApp
    def update(self, instance, validated_data):
        raise_errors_on_nested_writes('update', self, validated_data)

        if validated_data.get('class_id_id'):
            p = validated_data.pop('class_id_id')
            t = Class.objects.get(id=p)
            instance.class_id = t
            instance.class_id.save()

        instance.save()

        return instance
コード例 #36
0
    def build_obj(self, data=None):
        """ Much of this is copied from the create method
        of ModelSerializer in DRF, as we need to be able
        to create an object using the serializer without saving it,
        which the create method does not allow.
        """
        from rest_framework.utils import model_meta
        from rest_framework.serializers import raise_errors_on_nested_writes

        # Copy as validated_data is mutated
        if data == None:
            data = self.validated_data
        validated_data = copy.copy(data)

        raise_errors_on_nested_writes('create', self, validated_data)

        ModelClass = self.Meta.model

        # Remove many-to-many relationships from validated_data.
        # They are not valid arguments to the default `.create()` method,
        # as they require that the instance has already been saved.
        info = model_meta.get_field_info(ModelClass)
        many_to_many = {}
        for field_name, relation_info in info.relations.items():
            if relation_info.to_many and (field_name in validated_data):
                many_to_many[field_name] = validated_data.pop(field_name)

        try:
            instance = ModelClass(**validated_data)
        except TypeError as exc:
            msg = (
                'Got a `TypeError` when calling `%s.objects.create()`. '
                'This may be because you have a writable field on the '
                'serializer class that is not a valid argument to '
                '`%s.objects.create()`. You may need to make the field '
                'read-only, or override the %s.create() method to handle '
                'this correctly.\nOriginal exception text was: %s.' %
                (
                    ModelClass.__name__,
                    ModelClass.__name__,
                    self.__class__.__name__,
                    exc
                )
            )
            raise TypeError(msg)

        return instance
コード例 #37
0
 def update(self, instance, validated_data):
     """
         Since anonymous users should be able to vote a post, they should only
         be allowed to change the "votes" field, and to prevent users from
         voting a post by 1000 up or down in one request we'll only change "votes"
         by 1
     """
     serializers.raise_errors_on_nested_writes('update', self, validated_data)
     votes = validated_data.get('votes', self.instance.votes)
     if votes > 0:
         self.instance.votes += 1
     elif votes < 0:
         self.instance.votes -= 1
     else:
         self.instance.vote = self.instance.votes
     instance.save()
     return instance
コード例 #38
0
ファイル: serializers.py プロジェクト: AddictGuild/django-adt
    def update(self, instance, validated_data):
        user_updated.send(sender=self.__class__, instance=instance)

        raise_errors_on_nested_writes('update', self, validated_data)
        info = model_meta.get_field_info(instance)

        # Simply set each attribute on the instance, and then save it.
        # Note that unlike `.create()` we don't need to treat many-to-many
        # relationships as being a special case. During updates we already
        # have an instance pk for the relationships to be associated with.
        for attr, value in validated_data.items():
            if attr in info.relations and info.relations[attr].to_many:
                field = getattr(instance, attr)
                field.set(value)
            else:
                setattr(instance, attr, value)
        instance.save()

        return instance
コード例 #39
0
 def update(self, instance, validated_data):
     raise_errors_on_nested_writes('update', self, validated_data)
     for attr, value in validated_data.items():
         setattr(instance, attr, value)
     instance.save(self.context.get('request').user)
     return instance