How to update a database in Django through an illegal intermediate state?

I am trying to change some database records from one legal state to another, but the intermediate (partially updated) state is not legal. As an example, suppose I model lectures, each of which consists of several short topics in some order:

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'),) 

My test case:

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

Essentially, I'm trying to do:

 t0.order, t1.order = t1.order, t0.order 

and then save, but no matter which of the changed objects I saved, the β€œorder” will first have the same value as the other record. I could remove and redo it, but when the time comes to reorder several topics at once, it will be a pain. What is the cleanest way to do this?

+4
source share
1 answer

A dirty dirty solution ... you can reset and recreate a database constraint using the 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']) 
-1
source

Source: https://habr.com/ru/post/1386675/


All Articles