本文介绍了在Django中,JSONField为base_field的ArrayField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a GooglePlace model with a field to store the address_components being returned by Google Places API.

model.py

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

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

I am trying to store the data like this

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

但是我遇到了这个错误:

But I am getting this error :

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

'2018-04-26T07:49:02.101395+00:00'::timestamptz, ARRAY['{"l... ^ HINT: You will need to rewrite or cast the expression.

我尝试了json.dumps每个组件,进行编码.但是我认为我缺少一些愚蠢的东西.

I tried json.dumps each component, encode. But I think I am missing something silly.

任何帮助将不胜感激

这是示例响应:

"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"
      ]
   }
],

推荐答案

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

You don't need to wrap the json in an ArraField. You can store your address_components list directly into a JSONField.

这篇关于在Django中,JSONField为base_field的ArrayField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-29 22:31