django - Swapping values in a OneToOneField: IntegrityError -
i have following object:
from django.db import models class page(models.model): prev_sibling = models.onetoonefield('self', related_name='next_sibling', null=true, blank=true) i have several instances of these objects. let's say, a, b, c , d. have assigned sibling relationships such a has b prev_sibling, , c has d prev_sibling.
now imagine want swap b , d around. re-assign attributes, follows:
a.prev_sibling = d a.save() c.prev_sibling = b c.save() however, fails integrityerror, no longer satisfy uniqueness constraint implied onetoonefield after first save().
i tried wrapping code in transaction, hoping that make sure save occur atomically, , prevent temporary constraint breach, so:
from django.db import transaction transaction.atomic(): a.prev_sibling = d a.save() c.prev_sibling = b c.save() but did not work. right way resolve this?
edit: record: tried sequentially assigning , saving (as follows), 1 might expect, behaviour no different.
with transaction.atomic(): a.prev_sibling = d c.prev_sibling = b a.save() c.save()
you're violating database constraints. need clear other 1 before save database in 'valid' state. granted, after set them none, it's not technically desired state, it's valid 1 database constraints.
this should work you, risk losing relationship if bad happen between saving them none , setting properties.
page.objects.filter(id__in=[a.id, c.id]).update(prev_sibling=none) a.prev_sibling = d a.save() c.prev_sibling = b c.save()
Comments
Post a Comment