Jay
Jay

Reputation: 29

Setting ArrayField to null or []

files = fields.ArrayField(models.UUIDField(null=True), blank=True,
                              default=None)

So I have this line in my model, the task is to keep array of UUIDs of files in the field "files", but i still get an error

The array field was imported from postgres fields like so

from django.contrib.postgres import fields

and models was imported

from django.db import models

Here is the error while executing python manage.py migrate after python manage.py makemigrations

File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 447, in add_field
    self.execute(sql, params)
  File "/usr/local/lib/python3.7/site-packages/django/db/backends/base/schema.py", line 137, in execute
    cursor.execute(sql, params)
  File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute
    return super().execute(sql, params)
  File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: column "files" contains null values

Update: The thing is the field is should be optional, so if the client decides to upload a photo or any files related to this model later this should be done

Upvotes: 1

Views: 3247

Answers (1)

AKX
AKX

Reputation: 169051

I think you want an array of non-nullable UUIDs:

files = fields.ArrayField(models.UUIDField(), blank=True)

That is, the array itself may not contain nulls.

To initialize the field to an empty list, pass in a factory function (never a mutable object!); list(), as you know, returns an empty list.

files = fields.ArrayField(models.UUIDField(), blank=True, default=list)

If you do need to distinguish between NULL files and no files,

files = fields.ArrayField(models.UUIDField(), blank=True, null=True)

will do the trick.

(That said, are these files represented by other models? If so, you may really be looking for a ManyToManyField; this sort of array field has no referential integrity guarantees!)

Upvotes: 8

Related Questions