Home > Mobile >  Django REST Framework - Get reversed value of boolean field in serializer
Django REST Framework - Get reversed value of boolean field in serializer

Time:11-17

I have 2 models:

class Model(models.Model):
...

    related = models.ForeignKey(
        'RelatedModel',
        on_delete=models.CASCADE,
        related_name='related_model'
    )

class RelatedModel(models.Model):
...

    flag = models.BooleanField()

I need to pass value of 'flag' attribute of RelatedModel in Model instance serializer and additionally this value must be reversed i.e. if it is 'True', I should return 'False' as boolean data type.

Already implemented this with method:

class ModelSerializer(serializers.ModelSerializer):
    ...
    flag = serializers.SerializerMethodField()

    @staticmethod
    def get_flag(obj):
        return not obj.related.flag

    class Meta:
        model = Model
        fields = (
            ...
            flag
        )

But maybe there is opportunity to use only serializer fields like this but with reverse value?

flag = serializers.BooleanField(
        source='related.flag', read_only=True
    )

CodePudding user response:

If you need to reverse the value you can' t use a BooleanField, the simplest solution is to use a SerializerMethodField as you have already done. Or you could also create a custom field class, but that is more complicated.

  • Related