Django models 如何通过非法的中间状态更新Django中的数据库?
我试图将一些数据库条目从一个合法状态更改为另一个合法状态,但中间(部分更新)状态是不合法的。作为一个例子,假设我正在为讲座建模,每个讲座都由几个按一定顺序排列的简短主题组成:Django models 如何通过非法的中间状态更新Django中的数据库?,django-models,Django Models,我试图将一些数据库条目从一个合法状态更改为另一个合法状态,但中间(部分更新)状态是不合法的。作为一个例子,假设我正在为讲座建模,每个讲座都由几个按一定顺序排列的简短主题组成: class Lecture(models.Model): slug = models.TextField( help_text='Abbreviated name of lecture.' ) class Topic(models.Model): slug = models.Tex
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
然后保存,但我首先保存的任何修改对象都将具有与其他条目相同的“顺序”值。我可以删除并重新制作,但当一次要重新订购12个主题时,那将是一种痛苦。最干净的方法是什么?肮脏的解决方案。。。您可以使用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'])