5

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
               )
2
  • Why do you need to do this? Can this not be solved with two floats? Commented Feb 3, 2017 at 10:03
  • 1
    I know I can solve with two floats. I just want to know if I can use different field types inside an ArrayField. Commented Feb 3, 2017 at 10:04

3 Answers 3

4

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,
    )
)
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.