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

标签 python django postgresql django-models python-3.8

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

我尝试为电子邮件字段执行此操作,但这不起作用:

常量.py:

ORDER_STATUS_CHANGED = 'order_status_changed'
NEW_SIGNAL = 'new_signal'

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

)

模型.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 []``

最佳答案

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

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

default=['order_status_changed', 'new_signal']

要消除警告,您应该创建一个返回默认值的函数:
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

关于python - 如何将默认值数组添加到 ArrayField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60779234/

相关文章:

sql - 在 PostgreSQL 中选择第 1 列值相同但第 2 列值不同的行

python - 如何加载 csv 文件并将其内容存储到 python 中的 (numpy) 数组中?

c++ - Linux 中有哪些语音库可用?

Python 随机变量无法正常工作

python - vscode和docker已在使用(Errno 98)django的地址

java - JPA、Hibernate 与 c3p0 和 Postgres。检测数据库连接问题

python - PermissionError : [Errno 13] Permission denied: . deepface

python - 如何从每个页面访问 django-cms 中的所有页面对象?

django - 覆盖默认的 Django 翻译

postgresql - 文本字段相等