Home > Net >  DRF serializer's BooleanField returns null for empty ForeignKey field
DRF serializer's BooleanField returns null for empty ForeignKey field

Time:05-06

I want to add boolean fields has_video and has_gallery to my serializer.

Their values should be true if the ForeignKey fields of MyModel (video, gallery) have values, otherwise these values should be set to false.

models.py

class MyModel(models.Model):
    video = models.ForeignKey(
        to='videos.Video',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
    )
    gallery = models.ForeignKey(
        to='galleries.Gallery',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
    )

serializers.py

class MyModelSerializer(serializers.ModelSerializer):
    has_video = serializers.BooleanField(source='video', default=False)
    has_gallery = serializers.BooleanField(source='gallery', default=False)

The problem occurs when the video or gallery value of MyModel object is null. I expect the returned values to be false but it is null.

        "has_video": null,
        "has_gallery": null,

I try to set allow_null parameters to false but the result is the same (the values are still null).

has_video = serializers.BooleanField(source='video', default=False, allow_null=False)
has_gallery = serializers.BooleanField(source='gallery', default=False, allow_null=False)

When the video or gallery is not null, the serializer's fields return true as I expect. The problem is just about null/false values.

CodePudding user response:

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
  • Related