21๐
Arrays
First of all, letโs take a close look at this important text from the Postgresql Arrays document.
Tip: Arrays are not sets; searching for specific array elements can be
a sign of database misdesign. Consider using a separate table with a
row for each item that would be an array element. This will be easier
to search, and is likely to scale better for a large number of
elements.
Most of the time, you should not be using arrays.
JSONB
JSONB is available in Django as the JSONField type. This field is more scalable and flexible than array fields and can be searched more efficiently. However if you find yourself searching inside JSONB fields all the time the above statement about Arrays is equally valid for JSONB.
Now what do you have in your system? A an array that holds JSONB field. This is a disaster waiting to happen. Please normalize your data.
Recap
so when to use ArrayField?
On the rare occasion when you donโt need to search in that column and you donโt need to use that column for a join.
7๐
I have encountered the same scenario. Here is the way how I solved it
models.py
from django.contrib.postgres.fields.jsonb import JSONField as JSONBField
location = JSONBField(default=list,null=True,blank=True)
insert
model_object.location = [{"locations" : "loc1","amount":Decimal(100.00)},{"locations" : "loc2","amount":Decimal(200.25)}]
update
model_object.location.append({"locations" : "loc1","amount":Decimal(100.00)})
model_object.save()
This worked for me in
Django โ 2.0.2
Postgres โ 9.5
psycopg2 โ 2.7.4
python โ 3.4.3
- [Django]-Django substr / substring in templates
- [Django]-How does the get_or_create function in Django return two values?
- [Django]-Django Multiple Authentication Backend for one project
4๐
You can sidestep this issue by using the JSONField as the column field type with a list
as the root element.
from django.contrib.postgres.fields import JSONField
class MyDBArray(models.Model):
array_data = models.JSONField(default=list)
my_db_array = MyDBArray(array_data=[1, 2, 3])
my_db_array.save()
You would need to validate in the save
method that the array_data
field is actually list-like.
- [Django]-Handle `post_save` signal in celery
- [Django]-Django error: got multiple values for keyword argument
- [Django]-Is this the right way to do dependency injection in Django?
1๐
This was fixed in the latest unreleased version of Django 2.2a1
pip install Django==2.2a1
PS I believe that it will work with versions >= 2.2a1
- [Django]-Django: For Loop to Iterate Form Fields
- [Django]-Name '_' is not defined
- [Django]-Extend base.html problem
0๐
I guess the easiest way is to turn the field from an array of jsonfield into a jsonfield. Just add a key to the location_arr.
Related thread: ArrayField with JSONField as base_field in Django
- [Django]-Django Footer and header on each page with {% extends }
- [Django]-How to pass multiple values for a single URL parameter?
- [Django]-How to add superuser in Django from fixture