【问题标题】:How to get id from list in dictionary in the serializer django如何从序列化程序 django 中的字典列表中获取 id
【发布时间】:2023-03-28 01:27:01
【问题描述】:
CHOICE_FIELD_SET = {
    'dependent': [
        {'id': 1, 'name': "Spouse"},
        {'id': 2, 'name': "Children"},
        {'id': 3, 'name': "Parents"}
    ]
}

这是我的常量.py

 @staticmethod
    def validate_dependent_type(dependent_type):
        if dependent_type > util_constants.CHOICE_FIELD_SET['dependent'].extend('id'):
            raise serializers.ValidationError("Dependent can be of three types only")
        return dependent_type

这是我的 serializer.py

如何仅验证 id 3 希望你理解这个问题,如果不明白,请在评论中提问

【问题讨论】:

  • 所以需要检查依赖的id是否大于3?
  • 我需要限制此列表中是否存在依赖类型然后只执行否则显示错误

标签: django python-3.x list dictionary django-rest-framework


【解决方案1】:
CHOICE_FIELD_SET = {
'dependent': [
    {'id': 1, 'name': "Spouse"},
    {'id': 2, 'name': "Children"},
    {'id': 3, 'name': "Parents"}
]

}

def validate_dependent_type(dependent_type):
    # validate if dependent_type > dependant id list
    if dependent_type > max([d.get('id') for d in util_constants.CHOICE_FIELD_SET.get('dependent', [0])] or [0]):
        raise serializers.ValidationError("Dependent can be of three types only")
    return dependent_type

检查 depenpdant_type 是否大于依赖 id 列表。即使依赖列表为空,上述代码也能正常工作。

【讨论】:

    猜你喜欢
    • 2018-03-18
    • 1970-01-01
    • 2020-02-06
    • 2020-03-26
    • 2021-11-21
    • 2021-02-13
    • 2020-11-15
    • 2013-02-07
    • 2021-03-14
    相关资源
    最近更新 更多