[英]Django model save() - AttributeError: 'NoneType' object has no attribute 'append'
In my models.py
I want to extend the Django User model by adding an email_list.在我的
models.py
,我想通过添加 email_list 来扩展 Django 用户模型。
from django.contrib.postgres.fields import ArrayField
class User(AbstractUser):
email_list = ArrayField(models.EmailField(max_length=100), null=True, blank=True)
[...]
This email_list has to have the user email as default value.此 email_list 必须将用户电子邮件作为默认值。 I found that the best way to do this, is by overriding the
save()
method:我发现最好的方法是重写
save()
方法:
def save(self, *args, **kwargs):
self.email_list.append(self.email)
super(User, self).save(*args, **kwargs)
However, when I add a user I get the following error:但是,当我添加用户时,出现以下错误:
AttributeError: 'NoneType' object has no attribute 'append'
And the print(type(self.email_list))
, returns <type 'NoneType'>
而
print(type(self.email_list))
返回<type 'NoneType'>
What is wrong with the ArrayField
? ArrayField
有什么问题?
You should use a callabe such as list for the default value.您应该使用诸如列表之类的 callabe 作为默认值。
from django.contrib.postgres.fields import ArrayField
class User(AbstractUser):
email_list = ArrayField(models.EmailField(max_length=100), null=True, blank=True, default=list)
[...]
https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/fields/ https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/fields/
the initial None value is occurring because null=True, even if default=list.出现初始 None 值是因为 null=True,即使 default=list。 to avoid default value overriding, remove or set null to False
为避免覆盖默认值,删除或将 null 设置为 False
from django.contrib.postgres.fields import ArrayField
class User(AbstractUser):
email_list = ArrayField(models.EmailField(max_length=100), blank=True, default=list)
[...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.