python - 项目不存在时如何处理

标签 python django

我有一个简单的 for 循环,它迭代本地数据库中的所有对象。对于每个对象,我引用一个 presalesEngineer 并将该 ID 传递给 API 调用以检索 JSON 响应。但是,数据库中的某些记录没有 presalesEngineer 值。在这种情况下,当将错误的 URL 传递给 API 调用时,空字符串会引发 HttpError。当 presalesEngineer 不存在,因此 API 未传递空值时,我该如何处理?

View .py

objects = Opportunity.objects.all()

    for object in objects:
        try:
            ps_e = object.presalesEngineer
            if ps_e:
                presales_engineers = [cwObj.get_member_by_id(ps_e) for object in objects]
            else:
                presales_engineers = 'None'
        except NameError:
            presales_engineers = 'None'

最佳答案

此代码块应尝试获取对象的 presalesEngineer 或返回 None (请注意,字符串“None”不等于 pytohon 对象 None)

for object in objects:
    try:
        ps_e = object.presalesEngineer
        # Do stuff with an object you know for sure will not trigger an exception
        # Something like:
        # if ps_e != '': < the object is not an empty string
        # or
        # if ps_e: < the object is not None
        # after you pass whatever checks you deem necessary, you launch your API call.
    except AttributeError:
        # You can either pass here or return a None object/Empty list
        ps_e = None

可能的实现如下:

# Empty list of whatever you are searching for
engineers = []
for my_object in objects:
    try:
        ps_e = my_object.presalesEngineer
        # This is here to avoid none values in your API call
        if ps_e:
            # Just in case your API call falls
            # It will fail silently in this try codeblock
            try:
                # Assuming cwObj is your driver/API endpoint builder
                # And that you only get one single string as response
                # And that string is not some data structure that you need to split
                my_desired_id = cwObj.get_member_by_id(ps_e)
                engineers.append(my_desired_id)
            # Using bare except statements is not a good idea
            # Use HttpError here if you don't want to pass on any exception
            except:
                pass
    except AttributeError:
        # You can either pass here or return a None object/Empty list
        pass
print engineers

关于python - 项目不存在时如何处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57147513/

相关文章:

python - 从 0 开始重新启动 pandas timeseries 数据集时间戳

python - 使用 CNN 训练海量数据

javascript - 禁用 Javascript 时创建确认对话框页面

python - 获取 Django 对象并将其包装在 QuerySet 中返回的函数?

python - Django "Models aren' t 已加载”

python - Django 模型继承 : ForeignKey on parent, 没有对子模型的 related_name 访问

python - 从python中的长字符串中删除某些字符

python - Python 有像 Ruby 一样的 .methods 方法吗?

sql - 使用 Django ORM 执行复杂的自引用查询

python - Django:我必须在应用程序之前登录管理站点