如何将默认值数组添加到 ArrayField?

How to add a default array of values ​to ArrayField?

是否可以为 ArrayField 添加默认值?

我尝试对电子邮件字段执行此操作,但这没有用:

constants.py:

ORDER_STATUS_CHANGED = 'order_status_changed'
NEW_SIGNAL = 'new_signal'

NOTIFICATION_SOURCE = (
    (ORDER_STATUS_CHANGED, 'Order Status Changed'),
    (NEW_SIGNAL, 'New Signal'),

)

models.py:

from notifications import constants
from django.contrib.postgres.fields import ArrayField

class NotificationSetting(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='notification_setting')

    telegram = ArrayField(models.CharField(
        choices= constants.NOTIFICATION_SOURCE,
        max_length=30
    ), default=list)

    email = ArrayField(models.CharField(
        choices= constants.NOTIFICATION_SOURCE,
        max_length=16
    ), default=list(dict(constants.NOTIFICATION_SOURCE).keys()))

    class Meta:
        db_table = 'notification_settings'

    def __str__(self):
        return f'Notification setting for user {self.user}'

我认为覆盖模型的保存方法是不好的做法。

问题是在 django 管理站点中我看到创建对象时默认值不计算在内。 (UPD。Maibe 我的自定义 ChoiseArrayField 有问题)

我收到这条消息: WARNINGS: notifications.NotificationSetting.email: (postgres.E003) ArrayField default should be a callable instead of an instance so that it's not shared between all field instances. HINT: Use a callable instead, e.g., use列表instead of[]``

ArrayField 上的 default 属性 应该是可调用的。您可以在此处阅读更多相关信息:https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/.

直接放置在那里得到的结果 list(dict(constants.NOTIFICATION_SOURCE).keys()) 只是一个警告,因此它仍应将默认值添加到字段中。通过将此默认值直接放置在那里,它将在迁移中放入以下内容,并且这些值将在所有字段实例之间共享:

default=['order_status_changed', 'new_signal']

要消除警告,您应该创建一个 returns 默认值的函数:

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

并将函数作为字段的默认值:

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

通过这样做,警告将消失,您可以从函数中获得选择默认值的逻辑。

执行此操作后,在迁移中默认值将如下所示:

default=my_model.models.get_email_default