在Django中将JSONField作为base_field的ArrayField

时间:2018-04-26 07:51:13

标签: json django python-3.x django-models models

我有一个GooglePlace模型,其中包含一个字段,用于存储Google Places API返回的address_components。

model.py

address_components = ArrayField(JSONField(), null=True, blank=True)

我正在尝试存储像这样的数据

address_components = [component for component in google_place_details.get("address_components")]

但是我收到了这个错误:

  

列“address_components”的类型为jsonb [],但表达式为   输入文字[]第1行:......

     

'2018-04-26T07:49:02.101395 + 00:00':: timestamptz,ARRAY ['{“l ...                                                                ^提示:您需要重写或转换表达式。

我尝试了json.dumps每个组件,编码。但我觉得我错过了一些愚蠢的事情。

非常感谢任何帮助

这是样本回复:

"address_components":[  
   {  
      "long_name":"Chennai",
      "short_name":"Chennai",
      "types":[  
         "locality",
         "political"
      ]
   },
   {  
      "long_name":"Ramagiri Nagar",
      "short_name":"Ramagiri Nagar",
      "types":[  
         "sublocality_level_2",
         "sublocality",
         "political"
      ]
   },
   {  
      "long_name":"Velachery",
      "short_name":"Velachery",
      "types":[  
         "sublocality_level_1",
         "sublocality",
         "political"
      ]
   },
   {  
      "long_name":"Chennai",
      "short_name":"Chennai",
      "types":[  
         "administrative_area_level_2",
         "political"
      ]
   },
   {  
      "long_name":"Tamil Nadu",
      "short_name":"TN",
      "types":[  
         "administrative_area_level_1",
         "political"
      ]
   },
   {  
      "long_name":"India",
      "short_name":"IN",
      "types":[  
         "country",
         "political"
      ]
   },
   {  
      "long_name":"600042",
      "short_name":"600042",
      "types":[  
         "postal_code"
      ]
   }
],

2 个答案:

答案 0 :(得分:1)

您无需将json包装在ArraField中。您可以将address_components列表直接存储到JSONField

答案 1 :(得分:1)

这是一个已知错误https://code.djangoproject.com/ticket/28291

我已将我的模型重构为JSONField()

来自:address_components = ArrayField(JSONField(), null=True, blank=True)

收件人:address_components = JSONField(null=True, blank=True)