我有这个问题:http://www.goalbrecht.com/2014/09/django-get_or_create-makes-duplicates/
作者提供了很好的解决方案,但我仍然试图找出如何为重复密钥制作postgresql throw integrity错误?这是来自网站的代码:
class ExtendedManager(models.Manager):
# Note that this new method only works if database constraints are set up to throw
# integrity errors due to unique constraints in the database tables.
def get_or_create(self, *args, **kwargs):
try:
return super().get_or_create(*args, **kwargs)
except IntegrityError as e: # DB reports that an object with these params already exists!
# Try again - this time, the get() should succeed and we're good to go.
# If it fails again with an integrity error, send it to the caller
return super().get_or_create(*args, **kwargs)
当我添加对象时,它不会抛出任何错误,它只会创建重复项,即使模型中有unique = True。