我正在尝试将某些数据库条目从一个合法状态更改为另一个合法状态,但中间(部分更新)状态不合法。作为一个例子,假设我正在建模讲座,每个讲座都按照一些顺序由几个简短的主题组成:
class Lecture(models.Model):
slug = models.TextField(
help_text='Abbreviated name of lecture.'
)
class Topic(models.Model):
slug = models.TextField(
help_text='Abbreviated name of topic.'
)
lecture = models.ForeignKey(
Lecture,
help_text='The lecture this topic is part of.'
)
order = models.IntegerField(
help_text='Impose ordering on topics.'
)
class Meta:
unique_together = (('lecture', 'order'),)
我的测试用例是:
class TestTopicOrder(TestCase):
def test_reordering_topics(self):
# The lecture these topics are part of.
lecture = Lecture(title='Test Lecture', slug='lec')
lecture.save()
# Two topics 'zero' and 'one' in that order.
Topic(lecture=lecture, slug='zero', order=0).save()
Topic(lecture=lecture, slug='one, order=1).save()
# Try to invert the order.
t0 = Topic.objects.get(slug='zero')
t1 = Topic.objects.get(slug='one')
t0.order = 1
t1.order = 0
t0.save()
t1.save()
基本上,我正在尝试:
t0.order, t1.order = t1.order, t0.order
然后保存,但是我先保存的修改对象将具有与其他条目相同的“顺序”值。我可以删除并重新制作,但是当需要立即重新订购十几个主题时,这将是一个痛苦。最干净的方法是什么?
答案 0 :(得分:-1)
脏兮兮的解决方案......您可以使用south api删除并重新创建对数据库的限制:
from south.db import db
db.delete_unique('app_lecture', ['lecture', 'order'])
# do your stuff
# then reenable the unique constraint...
db.create_unique('app_lecture', ['lecture', 'order'])