简体   繁体   English

DRF 序列化程序的 BooleanField 为空 ForeignKey 字段返回 null

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

I want to add boolean fields has_video and has_gallery to my serializer.我想将 boolean 字段has_videohas_gallery添加到我的序列化程序中。

Their values should be true if the ForeignKey fields of MyModel (video, gallery) have values, otherwise these values should be set to false .如果 MyModel (video, gallery) 的 ForeignKey 字段有值,它们的值应该为true ,否则这些值应该设置为false

models.py模型.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序列化程序.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.当 MyModel object 的视频或图库值为 null 时会出现问题。我预计返回值为 false 但它是 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 ).我尝试将allow_null参数设置为false但结果是一样的(值仍然是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.当视频或画廊不是 null 时,序列化程序的字段如我所料返回 true。 The problem is just about null/false values.问题只是关于 null/false 值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM