Django ORM:结合使用F,MAX和GROUP BY

时间:2019-02-21 12:56:17

标签: python django django-queryset django-orm django-2.1

我有一个自定义模型管理器,该管理器重写了create方法。目标模型具有order_nbr字段,它表示项目的顺序。我想将order_nbr的MAX值加1。此处的关键是应将MAX值与GROUP BY结合使用。请看一下我的代码(仍然可能会受到竞争条件的影响):

class ContentOnPageModelManager(models.Manager):

    def create(self, **kwargs):
        if 'order_nbr' not in kwargs:
            try:
                order_nbr = ContentOnPage.objects.filter(page=kwargs['page']).latest('order_nbr').values('order_nbr')[0]
            except ContentOnPage.DoesNotExist:
                order_nbr = 0
            # TODO (dmitry): race condition
            kwargs['order_nbr'] = order_nbr + 1
        return super().create(**kwargs)



class ContentOnPage(models.Model):

    page = models.ForeignKey('Page', on_delete=models.CASCADE)
    video = models.ForeignKey('Video', null=True, on_delete=models.SET_NULL)
    audio = models.ForeignKey('Audio', null=True, on_delete=models.SET_NULL)
    text = models.ForeignKey('Text', null=True, on_delete=models.SET_NULL)
    order_nbr = models.PositiveIntegerField(default=0)

如何用类似以下的代码替换该代码:

kwargs['order_nbr'] = F(GROUP_BY('page').MAX('order_nbr')) + 1

^^^更像是伪代码

0 个答案:

没有答案