我想将布尔字段has_video
和has_gallery
添加到我的序列化程序中.
如果MyModel(视频、多媒体资料)的ForeignKey字段有值,则其值应为true
,否则这些值应设置为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)
当MyModel对象的video或gallery值为空时,就会出现问题.我希望返回的值为false,但它为null.
"has_video": null,
"has_gallery": null,
我try 将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)
当视频或图库不为空时,序列化程序的字段会像我预期的那样返回true.问题在于空值/假值.