[Solved]-How to add a default array of values ​to ArrayField?

19👍

The default property on an ArrayField should be a callable. You can read more about that here: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/.

What you are getting by placing directly there list(dict(constants.NOTIFICATION_SOURCE).keys()) is just a warning so it should still add the defaults to the field. By placing this default directly there it will put in the migrations the following thing and the values will be shared across all field instances:

default=['order_status_changed', 'new_signal']

To get rid of the warning you should create a function that returns the default value:

def get_email_default():
    return list(dict(constants.NOTIFICATION_SOURCE).keys())

and put the function as the default to the field:

email = ArrayField(models.CharField(
    choices= constants.NOTIFICATION_SOURCE,
    max_length=16
), default=get_email_default)

By doing this the warning will be gone and from the function you can have logic for choosing the default value.

After doing this, in the migrations the default value will look like this:

default=my_model.models.get_email_default

Leave a comment