'How to fill and access a Django ArrayField?

To solve my (kinda specific) problem, I found that I have to use Django ArrayField: https://docs.djangoproject.com/en/2.1/ref/contrib/postgres/fields/#arrayfield

I have defined it in my models.py file as

Bla = ArrayField(
        models.IntegerField(),
        size=4
        null=True
        )

But how do I actually put information inside? Ideally both a whole python list, as also at a single place.

And once it is in there, how can I retrieve it? Both on python side, as also in the .html file?

PS: I don't think that the whole background of the problem is relevant, so I omitted it for now, but I will of course provide all necessary details if anyone is interested.



Solution 1:[1]

You just assign a list of integers.

class M(models.Model):
    bla = ArrayField(models.IntegerField(), size=4, null=True)

m = M.objects.create(bla=[1, 3, 3, 7])

# (or, equivalently,)

m = M()
m.bla = [1, 3, 3, 7]
m.save()

# (or, equivalently,)

m = M(bla=[1, 3, 3, 7])
m.save()

Reading m.bla, you get back a list of integers, which you can access in Python or Django templates like any other list.

See also the documentation on the various extra lookups for ArrayFields.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1