ArrayField with JSONField as base_field in Django

喜你入骨 提交于 2021-01-28 09:01:16

问题


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 :

column "address_components" is of type jsonb[] but expression is of type text[] LINE 1: ...

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

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

Any help will be much appreciated

This is sample response :

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

回答1:


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




回答2:


This is a known bug https://code.djangoproject.com/ticket/28291.

I have refactored my model to JSONField()

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

To : address_components = JSONField(null=True, blank=True)



来源:https://stackoverflow.com/questions/50037589/arrayfield-with-jsonfield-as-base-field-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!