Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting values from a Django JSONField

Tags:

django

I'm trying to retrieve values from a JSONField in my model, but i'm getting an error:

'Api' object has no attribute '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)

According to the Django docs '__' is the correct way to filter on the JSON data, but maybe it's not the correct way to access it?

{"info": {"title": "Test API", "version": "1.0.0"}}
like image 353
redmamoth Avatar asked May 07 '26 04:05

redmamoth


1 Answers

Double-underscore syntax is only valid in things like filters and sorting, whether you're dealing with a JSON field or a traditional cross-table join.

The field gives you a dictionary. You use normal dictionary syntax from that point on.

self.openapi_spec['info']['title']
like image 103
Daniel Roseman Avatar answered May 09 '26 18:05

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!