0

I have a serializer in which I need to update the related model and return the updated value using the serializer method field.

class MultiUserSerializer(serializers.ModelSerializer):
    
    shared_user = UserBaseSerializer(required=False)
    enforce_mfa = serializers.SerializerMethodField(default=False, required=False)

    class Meta:
        model = MultiUser
        depth = 1
        fields = [
            'shared_user',
            'enforce_mfa',
        ]

    def update(self, instance, validated_data):
        
        if self.context['request'].data.get('enforce_mfa'):
            # Say enforce_mfa = True
            enforce_mfa = json.loads(str(self.context['request'].data.get('enforce_mfa')).lower())

            preference, create = Preference.objects.get_or_create(user=instance.shared_user)
            preference.enforce_mfa = enforce_mfa
            preference.save()

            print('This prints True: {}'.format(preference.enforce_mfa))

        instance_ = super().update(instance, validated_data)

        return instance_

    def get_enforce_mfa(self, obj):

        try:
            a = obj.shared_user.preference.enforce_mfa
            print('This remains False {}'.format(a))
            return a
        except ObjectDoesNotExist:
            return False  # Return False in case of preference does not exist.

After updating the Preference model inside the update() method, the value is updated successfully but the value returned from get_enforce_mfa() method is still the previous value.

Say if the previous value of enforce_mfa is False, and the value is updated to True, it still returns False from the get_enforce_mfa() method.

Anuj TBE
  • 9,198
  • 27
  • 136
  • 285
  • Have you tried using the `perform_update` instead of `update` ? You can add behavior that occurs before or after saving an object. – Klim Bim Apr 20 '21 at 13:41

2 Answers2

0

Use refresh_from_db():

    def get_enforce_mfa(self, obj):

        try:
            preference = obj.shared_user.preference
            preference.refresh_from_db()
            return preference.enforce_mfa
        except ObjectDoesNotExist:
            return False  # Return False in case of preference does not exist.

Here's the documentation link

nenadp
  • 798
  • 1
  • 7
  • 15
0

A similar question has been answered here.

The reason that it's not updating the field's value is because the 'SerializerMethodField' is read_only in DRF.

Nomi
  • 185
  • 2
  • 13