它是我的模型,我想在序列化器中使截图字段可选 -
class SbmWebsiteAdditionalScreenshot(TimeStampedModel):
website = models.ForeignKey(
'SbmWebsite', related_name='additional_screenshots')
screenshot = models.ImageField(
upload_to='website/interim/additional_screenshot/', blank=True)
associated_additional_screenshot = models.ForeignKey(
'websites.WebsiteAdditionalScreenshot',
related_name='sbn_website_associated_additional_screenshot',
null=True, editable=False, blank=True)
request_deletion = models.BooleanField(default=False, editable=False)
我尝试了这三个选项。
1
class SbmWebsiteAdditionalScreenshotSerializer(serializers.ModelSerializer):
is_interim = serializers.SerializerMethodField()
def get_is_interim(self, obj):
return True
class Meta:
model = SbmWebsiteAdditionalScreenshot
fields = [
'screenshot', 'associated_additional_screenshot',
'request_deletion',
'id', 'is_interim'
]
data = [{'id': 28, 'associated_additional_screenshot': None, 'is_interim': True}]
f= SbmWebsiteAdditionalScreenshotSerializer(data=data, many=True)
f.is_valid()
True
f.validated_data[0].items()
[]
2
class SbmWebsiteAdditionalScreenshotSerializer(serializers.ModelSerializer):
is_interim = serializers.SerializerMethodField()
screenshot = serializers.ImageField(required=False)
def get_is_interim(self, obj):
return True
class Meta:
model = SbmWebsiteAdditionalScreenshot
fields = [
'screenshot', 'associated_additional_screenshot',
'request_deletion',
'id', 'is_interim'
]
f= SbmWebsiteAdditionalScreenshotSerializer(data=data, many=True)
f.is_valid()
True
f.validated_data[0].items()
[]
3
class SbmWebsiteAdditionalScreenshotSerializer(serializers.ModelSerializer):
is_interim = serializers.SerializerMethodField()
screenshot = ImageField(allow_empty_file=True, use_url=True)
def get_is_interim(self, obj):
return True
class Meta:
model = SbmWebsiteAdditionalScreenshot
fields = [
'screenshot', 'associated_additional_screenshot',
'request_deletion',
'id', 'is_interim'
]
f= SbmWebsiteAdditionalScreenshotSerializer(data=data, many=True)
f.is_valid()
False
f.errors
[OrderedDict([('screenshot', [u'No file was submitted.'])])]
如何在不上传图像的情况下使ImageField可选并序列化数据?我要么得到空的dict或错误