2011-12-16 8 views
4

一部のデータベースエントリをある正当な状態から別の正当な状態に変更しようとしていますが、中間(部分的に更新された)状態は合法ではありません。Djangoのデータベースを不正な中間状態で更新するには?

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() 

、私がしようとしている例として、私はいくつかのために、いくつかの短いトピックで構成され、それぞれが講義を、モデル化していたとし

保存しますが、最初に保存した変更されたオブジェクトは、他のエントリと同じ「順序」値を持ちます。私は削除して再作成することができますが、一度に12のトピックを並べ替える時間が来たら、それは苦痛になるでしょう。これを行う最もクリーンな方法は何ですか?

答えて

-1

汚い汚いソリューション...あなたは南の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']) 
関連する問題