Search code examples
pythondjangodjango-modelsdjango-postgresql

Django ArrayField with different types


I need to configure a django.contrib.postgres.fields.ArrayField with a list of pairs in which the fist element is a float and the second, a small positive integer:

data = [[1.23, 3], [2.42, 1], [3.72, 29]]

How could I do this? Is it possible? I tried something like this, but didn't work:

class MyModel(models.Model):
    my_field = ArrayField(
                   models.FloatField(default=0),                        
                   models.PositiveSmallIntegerField(default=0),
                   null=True
               )

Solution

  • I just want to know if I can use different field types inside an ArrayField.

    No, this is not possible, it would involve a very confusing way to get the data out of the database, as well as no way of really setting the field type in the database to a concrete type.

    Instead, just use a two float fields

    my_field = ArrayField(
        ArrayField(
            models.FloatField(default=0),
            size=2,
        )
    )