本文整理汇总了Python中django.db.IntegrityError方法的典型用法代码示例。如果您正苦于以下问题:Python db.IntegrityError方法的具体用法?Python db.IntegrityError怎么用?Python db.IntegrityError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db
的用法示例。
在下文中一共展示了db.IntegrityError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_reminder_on
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import IntegrityError [as 别名]
def create_reminder_on(self, date, start_date, end_date):
if start_date > date or date > end_date:
# not timely, so ignore
return
if self.reminder_type == 'ROLE':
roles = Role.objects_fresh.filter(unit=self.unit, role=self.role).select_related('person')
recipients = [r.person for r in roles]
elif self.reminder_type in ['PERS', 'INST']:
recipients = [self.person]
else:
raise ValueError()
for recip in recipients:
ident = '%s_%s_%s' % (self.slug, recip.userid_or_emplid(), date.isoformat())
# ident length: slug (50) + userid/emplid (9) + ISO date (10) + _ (2) <= 71
rm = ReminderMessage(reminder=self, sent=False, date=date, person=recip, ident=ident)
with transaction.atomic():
try:
rm.save()
except IntegrityError:
# already been created because we got IntegrityError on rm.ident
pass
示例2: save
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import IntegrityError [as 别名]
def save(self, *args, **kwargs):
"""Save the model."""
name_max_len = self._meta.get_field("name").max_length
if len(self.name) > name_max_len:
self.name = self.name[: (name_max_len - 3)] + "..."
for _ in range(MAX_SLUG_RETRIES):
try:
# Attempt to save the model. It may fail due to slug conflict.
with transaction.atomic():
super().save(*args, **kwargs)
break
except IntegrityError as error:
# Retry in case of slug conflicts.
if "{}_slug".format(self._meta.db_table) in error.args[0]:
self.slug = None
continue
raise
else:
raise IntegrityError(
"Maximum number of retries exceeded during slug generation"
)
示例3: save
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import IntegrityError [as 别名]
def save(self, must_create=False):
"""
Saves the current session data to the database. If 'must_create' is
True, a database error will be raised if the saving operation doesn't
create a *new* entry (as opposed to possibly updating an existing
entry).
"""
if self.session_key is None:
return self.create()
obj = Session(
session_key=self._get_or_create_session_key(),
session_data=self.encode(self._get_session(no_load=must_create)),
expire_date=self.get_expiry_date()
)
using = router.db_for_write(Session, instance=obj)
try:
with transaction.atomic(using=using):
obj.save(force_insert=must_create, using=using)
except IntegrityError:
if must_create:
raise CreateError
raise
示例4: set_span_element
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import IntegrityError [as 别名]
def set_span_element(sender, instance, **kwargs):
if (instance.resource_type in (sender.OCR,)) or (instance.oa_annotation['annotatedBy']['name'] == "ocr"):
try:
instance.oa_annotation['annotatedBy'] = {'name': 'ocr'}
instance.owner = User.objects.get_or_create(username='ocr', name='OCR')[0]
character_count = len(instance.content)
# 1.6 is a "magic number" that seems to work pretty well ¯\_(ツ)_/¯
font_size = instance.h / 1.6
# Assuming a character's width is half the height. This was my first guess.
# This should give us how long all the characters will be.
string_width = (font_size / 2) * character_count
# And this is what we're short.
space_to_fill = instance.w - string_width
# Divide up the space to fill and space the letters.
letter_spacing = space_to_fill / character_count
# Percent of letter spacing of overall width.
# This is used by OpenSeadragon. OSD will update the letter spacing relative to
# the width of the overlayed element when someone zooms in and out.
relative_letter_spacing = letter_spacing / instance.w
instance.content = "<span id='{pk}' data-letter-spacing='{p}'>{content}</span>".format(pk=instance.pk, content=instance.content, p=str(relative_letter_spacing))
instance.style = ".anno-{c}: {{ height: {h}px; width: {w}px; font-size: {f}px; }}".format(c=(instance.pk), h=str(instance.h), w=str(instance.w), f=str(font_size))
# TODO Is this actually how this should be handeled? If not, remove the import of `IntegrityError`
except (ValueError, ZeroDivisionError, IntegrityError) as error:
instance.content = ''
logger.warning("WARNING: {e}".format(e=error))
示例5: destroy
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import IntegrityError [as 别名]
def destroy(self, request, *args, **kwargs):
"""Delete a source."""
source = self.get_object()
manager = ProviderBuilder(request.user.identity_header.get("encoded"))
for _ in range(5):
try:
manager.destroy_provider(source.koku_uuid)
except IntegrityError as error:
LOG.warning(f"Retrying Source delete due to error: {error}")
except Exception as error: # catch everything else. return immediately
msg = f"Source removal resulted in UNKNOWN error: {type(error).__name__}: {error}"
LOG.error(msg)
return Response(msg, status=500)
else:
return super().destroy(request, *args, **kwargs)
LOG.error("Failed to remove Source")
return Response("Failed to remove Source", status=500)
示例6: test_deferred_error
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import IntegrityError [as 别名]
def test_deferred_error(self):
"""
Checks that an error occurring during the end of a transaction
has no impact on future queries.
"""
with connection.cursor() as cursor:
cursor.execute(
'CREATE TABLE example ('
'id int UNIQUE DEFERRABLE INITIALLY DEFERRED);')
with self.assertRaises(IntegrityError):
with transaction.atomic():
with self.assertNumQueries(1):
list(Test.objects.all())
cursor.execute(
'INSERT INTO example VALUES (1), (1);'
'-- ' + Test._meta.db_table) # Should invalidate Test.
with self.assertNumQueries(1):
list(Test.objects.all())
示例7: save
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import IntegrityError [as 别名]
def save(self, must_create=False):
"""
Save the current session data to the database. If 'must_create' is
True, raise a database error if the saving operation doesn't create a
new entry (as opposed to possibly updating an existing entry).
"""
if self.session_key is None:
return self.create()
data = self._get_session(no_load=must_create)
obj = self.create_model_instance(data)
using = router.db_for_write(self.model, instance=obj)
try:
with transaction.atomic(using=using):
obj.save(force_insert=must_create, force_update=not must_create, using=using)
except IntegrityError:
if must_create:
raise CreateError
raise
except DatabaseError:
if not must_create:
raise UpdateError
raise
示例8: handle
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import IntegrityError [as 别名]
def handle(self, *args, **options):
username = options['username']
password = options['password']
try:
validate_password(password, self.UserModel(username=username))
except ValidationError as err:
self.stderr.write('\n'.join(err.messages))
else:
try:
self.UserModel.objects.create_user(username=username, password=password)
except IntegrityError as e:
self.stderr.write(f'User already exists: {str(e)}')
else:
self.stdout.write(f"password: {password}")
示例9: test_allows_uniqueness_with_many_dead
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import IntegrityError [as 别名]
def test_allows_uniqueness_with_many_dead(self):
first = Person(name='collision')
first.save()
second = Person(name='collision')
# Uniqueness constraint should prevent a second live object with the
# same name.
with transaction.atomic():
self.assertRaises(IntegrityError, second.save)
# Should be able to have several dead objects with same name
first.live = False
first.save()
# Now we can save and delete second
second.save()
second.live = False
second.save()
third = Person(name='collision')
third.save()
self.assertEqual(Person.all_objects.count(), 3)
# Resurrecting one of the dead dupes should violate uniqueness
first.live = True
with transaction.atomic():
self.assertRaises(IntegrityError, first.save)
示例10: do_main
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import IntegrityError [as 别名]
def do_main(path="/data/assessor_data.csv"):
with open(path) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
loc_id = row["LOC_ID"]
try:
parcel = Parcel.objects.filter(loc_id=loc_id)[0]
for field, value in row.items():
handler = known_field_handler.get(field)
if handler:
handler(parcel, value)
else:
attribute = Attribute(parcel=parcel,
name=field,
value=value)
attribute.save()
except IntegrityError as err:
pass
except IndexError as err:
# No such Parcel exists
logger.warn("No parcel exists with loc_id '%s'", loc_id)
示例11: update_realm_custom_profile_field
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import IntegrityError [as 别名]
def update_realm_custom_profile_field(request: HttpRequest, user_profile: UserProfile,
field_id: int,
name: str=REQ(default=''),
hint: str=REQ(default=''),
field_data: ProfileFieldData=REQ(default={},
converter=ujson.loads),
) -> HttpResponse:
realm = user_profile.realm
try:
field = CustomProfileField.objects.get(realm=realm, id=field_id)
except CustomProfileField.DoesNotExist:
return json_error(_('Field id {id} not found.').format(id=field_id))
if field.field_type == CustomProfileField.EXTERNAL_ACCOUNT:
if is_default_external_field(field.field_type, ujson.loads(field.field_data)):
return json_error(_("Default custom field cannot be updated."))
validate_custom_profile_field(name, hint, field.field_type, field_data)
try:
try_update_realm_custom_profile_field(realm, field, name, hint=hint,
field_data=field_data)
except IntegrityError:
return json_error(_('A field with that label already exists.'))
return json_success()
示例12: register_remote_push_device
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import IntegrityError [as 别名]
def register_remote_push_device(request: HttpRequest, entity: Union[UserProfile, RemoteZulipServer],
user_id: int=REQ(validator=check_int), token: str=REQ(),
token_kind: int=REQ(validator=check_int),
ios_app_id: Optional[str]=None) -> HttpResponse:
server = validate_bouncer_token_request(entity, token, token_kind)
try:
with transaction.atomic():
RemotePushDeviceToken.objects.create(
user_id=user_id,
server=server,
kind=token_kind,
token=token,
ios_app_id=ios_app_id,
# last_updated is to be renamed to date_created.
last_updated=timezone.now())
except IntegrityError:
pass
return json_success()
示例13: test_emptyfield
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import IntegrityError [as 别名]
def test_emptyfield(self):
m = self._get_mailinglist()
p = self._get_participant()
values = {
'author': p,
'timestamp': datetime.datetime.utcnow(),
'subject': '',
'message_id': 'abc'
}
for key in values:
kwargs = values.copy()
kwargs[key] = None
sid = transaction.savepoint()
with self.assertRaises(ValueError if key == 'author'
else IntegrityError):
# ForeignKeys throw a ValueError instead of IntegrityError.
Post.objects.create(**kwargs)
transaction.savepoint_rollback(sid)
示例14: edit_category
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import IntegrityError [as 别名]
def edit_category(request, slug=None, parent_slug=None):
form = CategoryForm()
category = ProductCategory()
if slug is not None:
category = get_object_or_404(ProductCategory, slug=slug)
form = CategoryForm(instance=category)
if parent_slug is not None:
parent = get_object_or_404(ProductCategory, slug=parent_slug)
form = CategoryForm(initial={'parent': parent.pk})
if request.method == "POST":
form = CategoryForm(request.POST, instance=category)
if form.is_valid():
try:
category = form.save()
except IntegrityError:
error = _(u'Category %s already exists') % category.title
messages.error(request, error)
return redirect(list_products)
messages.success(request, _(u"Category %s saved") % category.title)
return redirect(category)
else:
messages.error(request, form.errors)
return redirect(list_products)
return render(request, "products/category_form.html", locals())
示例15: edit_gsx_account
# 需要导入模块: from django import db [as 别名]
# 或者: from django.db import IntegrityError [as 别名]
def edit_gsx_account(request, pk=None):
object_list = GsxAccount.objects.all()
title = GsxAccount._meta.verbose_name_plural
if pk is None:
act = GsxAccount()
else:
act = GsxAccount.objects.get(pk=pk)
form = GsxAccountForm(instance=act)
if request.method == 'POST':
form = GsxAccountForm(request.POST, instance=act)
if form.is_valid():
try:
act = form.save()
cache.delete('gsx_session')
try:
act.test()
messages.success(request, _(u'%s saved') % act.title)
return redirect(list_gsx_accounts)
except gsxws.GsxError as e:
messages.warning(request, e)
except IntegrityError:
transaction.rollback()
msg = _('GSX account for this sold-to and environment already exists')
messages.error(request, msg)
return render(request, 'admin/gsx/form.html', locals())