mongoengin中ListField的极限长度

2024-09-24 20:35:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以在没有if条件的情况下限制mongoengie中ListField数据的长度吗?在

我需要这样的东西:

list = db.ListField(IntField(), max_length = 24)

在我的document中。在

或者当我的列表要更新时,我必须检查它的长度,如果我的列表长度超过24,就不要更新它!在


Tags: 数据列表dbif情况条件documentlength
1条回答
网友
1楼 · 发布于 2024-09-24 20:35:29

ListField中没有这样的内置功能,但是您可以让您的自定义ListField提供一个max_length属性:

class MyListField(ListField):
    def __init__(self, max_length=None,  **kwargs):
        self.max_length = max_length
        super(MyListField, self).__init__(**kwargs)

    def validate(self, value):
        super(MyListField, self).validate(value)

        if self.max_length is not None and len(value) > self.max_length:
            self.error('Too many items in the list')

相关问题 更多 >