【问题标题】:'<=' not supported between instances of 'str' and 'datetime.timedelta' in DjangoDjango 中的“str”和“datetime.timedelta”实例之间不支持“<=”
【发布时间】:2021-10-11 22:20:37
【问题描述】:

这里我要验证 start_time 的值在大于等于 0 小于等于 video_duration 的范围内,

models.py

class VideoBookmark(BaseModel, SoftDelete):    
    start_time = models.DurationField(default=timedelta())
    end_time = models.DurationField(default=timedelta())
    

序列化器.py

class VideoBookmarkSerializer(serializers.ModelSerializer):
    class Meta:
        model = VideoBookmark
        fields = ('start_time', 'end_time',)

    def validate(self,data):
           ......

        video_duration = VideoDetails.objects.get(video=video_id).duration
        if not "00:00:00" <= data['start_time'] < video_duration:
            raise ValidationError('start time')

        return data

错误

'<=' not supported between instances of 'str' and 'datetime.timedelta'

那么,我来回答一下如何正确指代“大于等于零或小于video_duration”

【问题讨论】:

    标签: django-models django-rest-framework django-serializer


    【解决方案1】:

    data['start_time'] 是以微秒表示的时间对象。要将其与零进行比较(我认为这是 00:00:00 应该是的),您可以这样做:

    if not 0 <= int(data['start_time'].total_seconds()/1000)
    

    您还在与 video_duration 进行比较,因此您应该确保它也是以微秒为单位的。

    【讨论】:

    • 谢谢,但这又犯了一个错误,我终于得到了答案 "total_seconds ()" >>> "if not 0
    • 嗨,很抱歉。我已经更正了答案。这应该可行,如果您需要不同的时间表达方式,您可以编辑除法。
    猜你喜欢
    • 1970-01-01
    • 2018-09-08
    • 2020-05-19
    • 2021-08-10
    • 2019-11-18
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    相关资源
    最近更新 更多