Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 1.8 ArrayField append & extend

Tags:

Django 1.8 will come with new advanced field types including ArrayField these rely on PostgreSQL and are implemented at a DB level.

PostgreSQL's array field implements an append method.

However I can't find any documentation on appending an item to an ArrayField. This would clearly be very useful as it would allow the field to be updated without transferring its entire contents from the db then back to it.

Is this possible? If not will it be possible in future? Any pointers to docs I've missed would be much appreciated.

To clarify what I'm asking about, this would be great:

Note: this is fantasy code and I assume won't work (I haven't tried)

# on model: class Post(models.Model):     tags = ArrayField(models.CharField(max_length=200))  # somewhere else: p = Post.objects.create(tags=[str(i) for i in range(10000)]) p.tags.append('hello') 

Is there currently any way of doing this without resorting to raw sql?

like image 604
SColvin Avatar asked Mar 12 '15 16:03

SColvin


1 Answers

Note: OP code will absolutely work. We just need to save the model (because these is just a model field, not relation). Let's see:

>>> p = Post.objects.create(tags=[str(i) for i in range(10000)]) >>> p.tags.append("working!") >>> p.save() >>> working_post = Post.objects.get(tags__contains=["working!"]) <Post: Post object> >>> working_post.tags[-2:] [u'9999', u'working!'] 

Going deeper

Django gets ArrayField as python list

Code reference

Everything you could do with list, you can do with ArrayField. Even sorting

Django saves ArrayField as python list

Code reference

These means that it saves structure and elements of python list.

like image 156
Daniil Ryzhkov Avatar answered Sep 29 '22 11:09

Daniil Ryzhkov