【发布时间】:2021-08-08 20:26:24
【问题描述】:
我已阅读此主题: get_or_create throws Integrity Error
但仍然不完全理解 get_or_create 何时返回 False 或 IntegrityError。
我有以下代码:
django_username = 'me'
user = get_user_model().objects.filter(username=django_username).first()
action_history, action_added = ActionModel.objects.get_or_create(
date=date_obj, # date object
account_name=unique_name, # e.g. account1234
target=follower_obj, # another model in django
user=user, # connected django user
defaults={'identifier': history['user_id']}
)
虽然模型看起来像:
class ActionModel(models.Model):
"""
A model to store action history.
"""
identifier = models.BigIntegerField(
_("identifier"), null=True, blank=True) # target id
account_name = models.CharField(_("AccountName"), max_length=150, null=True, blank=True) # account name of the client
date = models.DateField(_("Date"), auto_now=False, auto_now_add=False) # action date
target = models.ForeignKey(Follower, verbose_name=_("Target"), on_delete=models.CASCADE) # username of the done-on action
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
null=True,
editable=False,
db_index=True,
) # django user that performed the action
class Meta:
verbose_name = _("Action")
verbose_name_plural = _("Actions")
unique_together = [
['account_name','date','target'],
]
有时它会返回 IntegrityError,有时(当存在唯一约束时,它会在创建时返回 False)。
【问题讨论】:
-
文档说:> 如果需要创建一个对象并且数据库中已经存在密钥,则会引发 IntegrityError。
-
@MarkR。为什么它没有在创建之前的获取中被捕获?我将所有唯一值发送给它!