2

I have custom model

class customModel(models.Model):
    contents = models.TextField(null=True)

and another customModel with ArrayField

from django.contrib.postgres.fields import ArrayField
class customModel2(models.Model):
    ArrayField(customModel()):

but it raised errors AttributeError: 'customModel' object has no attribute 'set_attributes_from_name'

ArrayField(customModel) also raised similar errors.

What are the proper method to define an arrayfield with custom model as base field ?

1 Answers1

0

The error says that you didnt set name attribute. Do like this

from django.db import models
class CustomModel2(models.Model):
    # making an array of foreign keys of customModel
    # you can also use models.Integer etc
    myArray = ArrayField(
            models.ForeignKey(customModel, on_delete=models.CASCADE),
            size=8,
        )

Hashir
  • 390
  • 5
  • 20
  • Also, this might be helpful since youre using arrayField https://stackoverflow.com/a/51893414/11979793 – Hashir May 22 '20 at 21:05
  • It's not possible to use a ForeignKey as a base field for an ArrayField, see this https://stackoverflow.com/questions/35957837/trying-to-make-a-postgresql-field-with-a-list-of-foreign-keys-in-django – ldocao Jun 17 '20 at 15:45
  • @Idocao The restriction is of Postgres, not Django. It can be implemented in other fields. The Question does not mention the use of Postgres. Alternatively, I provided with the manytomany field solution in the first comment. – Hashir Jun 17 '20 at 18:17
  • @Hashir, `ArrayField` is found in `django.contrib.postgres.fields`. See the `postgres` in the package name? It's not implemented for any other database in Django. – Bobort May 26 '23 at 21:48