[Django]-DRF serializer's BooleanField returns null for empty ForeignKey field

3👍

This is the approach I have followed in one of my project.

class MyModelSerializer(serializers.ModelSerializer):
    has_video = serializers.SerializerMethodField('get_has_video', read_only=True)
    has_gallery = serializers.SerializerMethodField(source='get_has_gallery', read_only=True)
    # ... Your other fields 
    class Meta:
        model = "Your model name"
        fields = ("your model fields",
                  ,"has_video", "has_gallery") # include the above two fields
        
    def get_has_video(self, obj):
        # now your object should be having videos then you want True so do this like this
        return True if obj.video else False
    
    def get_has_gallery(self, obj):
        # now your object should be having galleries then you want True so do this like this
        return True if obj.gallery else False

Leave a comment