首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何通过非法的中间状态更新Django中的数据库?

如何通过非法的中间状态更新Django中的数据库?
EN

Stack Overflow用户
提问于 2011-12-16 18:22:44
回答 1查看 98关注 0票数 4

我正在尝试将一些数据库条目从一个合法状态更改为另一个合法状态,但中间(部分更新)状态是不合法的。举个例子,假设我正在模拟讲座,每个讲座都由几个简短的主题按一定的顺序组成:

代码语言:javascript
运行
复制
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'),)

我的测试用例是:

代码语言:javascript
运行
复制
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()

从本质上讲,我想做的是:

代码语言:javascript
运行
复制
t0.order, t1.order = t1.order, t0.order

然后保存,但无论我首先保存的是哪个修改过的对象,它都将具有与其他条目相同的“order”值。我可以删除并重新创建,但当需要一次对十几个主题进行重新排序时,这将是一件痛苦的事情。做这件事最干净的方法是什么?

EN

回答 1

Stack Overflow用户

发布于 2012-01-23 11:09:16

肮脏的解决方案..。您可以使用south api删除并重新创建对数据库的限制:

代码语言:javascript
运行
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8532782

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档