我想将布尔字段has_videohas_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.问题在于空值/假值.

推荐答案

这是我在一个项目中采用的方法.

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

Python相关问答推荐

剪切间隔以添加特定日期

为什么我的sundaram筛这么低效

在Docker容器(Alpine)上运行的Python应用程序中读取. accdb数据库

pandas:在操作pandora之后将pandora列转换为int

如何在Pandas中用迭代器求一个序列的平均值?

为什么按下按钮后屏幕的 colored颜色 保持不变?

用LAKEF划分实木地板AWS Wrangler

根据边界点的属性将图划分为子图

如何计算Pandas 中具有特定条件的行之间的天差

FASK集合变量未更新(HTML)中的值

如何在子窗口中正确设置和获取tkinter旋转框的值?

我如何沿着我的图表绘制一条线来显示哪里的数据密度最高?

删除特定单词后面的单词

从单个RBG图片开始创建12个多通道图像

将MultiIndex列的级别转换为具有值的列(取消堆叠列)

支持向量机模型突出错误的数据点作为支持向量

如果没有强制转换Numy数组,则通过ctype将Numy数组传递给C函数会产生错误的结果

WinError 193%1不是有效的Win32应用程序.AZ二头肌

如何计算数据集中的类别值并将求和转换为新的数据集?

为什么一些地块有网格线,而另一些地块没有网格线?