gpt4 book ai didi

python - Django get_or_create 返回 False

转载 作者:行者123 更新时间:2023-11-28 21:38:54 24 4
gpt4 key购买 nike

我正在创建一个填充脚本,从 MysqlDatabase 到 Django 模型。
我正在循环接收来自 Mysql 的数据,一切顺利。

现在我必须将它写入 Django 数据库...

mdl, succeeded = models.User.objects.get_or_create(
name=name,
password=password,
email=email
)

我正在打印成功所以我可以看到反馈是什么,但它给我的只是False

我的 Django 模型 User 已编辑,因此所有字段都可以是 blank 并允许 NULL 或具有默认值

我的模型用户:

username = models.CharField(max_length=20, blank=True, null=True)
slug = models.SlugField(null=True, blank=True)
email = models.EmailField(unique=True, null=True)
name = models.CharField("First and last name", max_length=100)
uses_metric = models.BooleanField(default=True)
position = models.CharField("Position", max_length=70, blank=True, null=True,)
utility = models.ForeignKey(Utility, default=1, blank=True, null=True)
supplier = models.ForeignKey(Supplier, default=1, blank=True, null=True)
currency = models.ForeignKey(Currency, default=1)
phone = models.CharField("Direct phone number", max_length=40, blank=True, default='+')
gets_notifications_on_reply = models.BooleanField("Receive notifications", default=False)
memberlist = models.BooleanField("Show member in memberslist", default=True)
registration_date = models.IntegerField(default=floor(time.time()), blank=True, null=True)
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_('Designates whether the user can log into this site.'),
)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Deselect this instead of deleting accounts.'
),
)
USERNAME_FIELD = 'email'

最佳答案

请检查您的数据库。这意味着您要从那里查询的用户对象已经存在。这可能是由于对象已经存在或者您的代码没有使用正确的数据库。由于迁移,经常使用多个数据库,这也可能是一个问题。

According to the Django documentation , get_or_create() 不返回一个对象和一个状态 succeeded 而是一个标志 created ,它指示这个对象是新创建的还是已经存在于数据库中。如果它已经存在,则 created 标志(在您的代码中为 succeeded)为 False

如果你想确保错误不是由对象已经存在引起的,取一个 created 为 false 的数据对,并尝试使用模型的 get() 检索它 方法。如果这会抛出 DoesNotExist 错误,则说明是其他问题。如果它返回一个对象,则该对象已经存在。

关于python - Django get_or_create 返回 False,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47549788/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com