插入新数据后如何重新排序优先级数据?

时间:2019-07-09 16:29:59

标签: python django django-models

当前使用Django Form等构建Help Ticket应用。 我正在尝试为模型创建一个“优先级”字段,该优先级编号不应重复其本身,如果已经存在新的优先级集,则应相应地对其他优先级进行重新排序。因此,不得复制优先级

我在Django中相对较新。我很难理解如何修改我的models.py,以便我可以创建一种方法,该方法将在每次单击“提交”后发送“发布”请求时执行某个命令来更新其他现有的“优先级”按钮

models.py

from django.db.models import F
from django.db import models

class Request(models.Model):
    title = models.CharField(max_length=255, unique=True)
    description = models.TextField(blank=True, null=True)
    priority = models.PositiveIntegerField()


    # This is what I have tried:
    def reorder_priority(self):
        existing_feature = Request.objects.get(priority=self.priority)
        foo = Request.objects.filter(priority__gte=existing_feature.priority)
        foo.update(priority=F('priority') + 1)
        foo.save()

    def __str__(self):
        return self.title

例如:

标题1,优先级= 1

标题2,优先级= 2

标题3,优先级= 3

用户添加一个新的TitleX,优先级= 3, 预期的输出:

标题3,优先级= 4

总体:

标题1,优先级= 1

标题2,优先级= 2

TitleX,优先级= 3

标题3,优先级= 4

1 个答案:

答案 0 :(得分:0)

我想出了这个解决方案,它以我想要的方式工作。随时对此发表评论。

models.py

 def save(self, **kwargs):
        # try to check if there is any existing priority that is duplicated:
        try:
            existing_feature = Request.objects.get(priority=self.priority)
            foo = Request.objects.filter(priority__gte=existing_feature.priority)
            if foo.count() > 0:
                foo.update(priority=F('priority') + 1)

            super(Request, self).save(**kwargs)

        except:
            super(Request, self).save(**kwargs)