【问题标题】:Getting values from a Django JSONField从 Django JSONField 获取值
【发布时间】:2018-10-27 19:50:25
【问题描述】:

我正在尝试从模型中的 JSONField 检索值,但出现错误:

'Api' 对象没有属性 'openapi_spec__info__title'

class Api(models.Model):
''' Model to hold infomation on the API '''

# JSONB field to hold the OpenAPI spec
openapi_spec = JSONField()

# Derive product name from the OpenAPI spec, since it's a mandatory field
def _get_product_name(self):
    return self.openapi_spec__info__title
product_name = property(_get_product_name)

根据 Django 文档,“__”是过滤 JSON 数据的正确方法,但可能不是访问它的正确方法?

{"info": {"title": "Test API", "version": "1.0.0"}}

【问题讨论】:

    标签: django


    【解决方案1】:

    双下划线语法仅在过滤器和排序等方面有效,无论您处理的是 JSON 字段还是传统的跨表连接。

    该字段为您提供字典。从那时起,您将使用普通的字典语法。

    self.openapi_spec['info']['title']
    

    【讨论】:

    • 太棒了,谢谢!关于我唯一没有尝试过的该死的事情:-)
    猜你喜欢
    • 2017-04-12
    • 2019-12-25
    • 2020-10-16
    • 2019-12-25
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 2016-07-23
    相关资源
    最近更新 更多