我正在尝试将一些数据库条目从一个合法状态更改为另一个合法状态,但中间(部分更新)状态是不合法的。举个例子,假设我正在模拟讲座,每个讲座都由几个简短的主题按一定的顺序组成:
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然后保存,但无论我首先保存的是哪个修改过的对象,它都将具有与其他条目相同的“order”值。我可以删除并重新创建,但当需要一次对十几个主题进行重新排序时,这将是一件痛苦的事情。做这件事最干净的方法是什么?
发布于 2012-01-23 11:09:16
肮脏的解决方案..。您可以使用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'])https://stackoverflow.com/questions/8532782
复制相似问题