msampaio
msampaio

Reputation: 3433

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
               )

Upvotes: 5

Views: 4733

Answers (3)

MD. SHIFULLAH
MD. SHIFULLAH

Reputation: 1731

You can Try this:

from django.contrib.postgres.fields import ArrayField
from django.db import models

class Author(models.Model):
   name = models.CharField(max_length=1024)
   books_list = ArrayField(
       models.CharField(max_length=1024)
   )

Upvotes: 0

psilocybin
psilocybin

Reputation: 1115

If you really need this functionality, you could try JSONField:

class MyModel(models.Model):
    my_field = JSONField()

And store '[[1.23, 3], [2.42, 1], [3.72, 29]]' in this, though it does raise questions about the design of your data model.

Upvotes: 1

Sayse
Sayse

Reputation: 43300

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,
    )
)

Upvotes: 4

Related Questions