Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 721
Maxim Moloshenko Avatar asked Oct 27 '25 10:10

Maxim Moloshenko


1 Answers

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.

like image 97
AKX Avatar answered Oct 29 '25 01:10

AKX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!