Django ORM如何在查询中引用另一行? [英] Django ORM how to reference to another row in query?
本文介绍了Django ORM如何在查询中引用另一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有下表'book':
I have the following table 'book':
id shelf position (on shelf)
1 2 3
2 1 1
3 1 2
4 2 2
5 2 1
我需要将book4移到书架1的末尾,因此我需要将
book4的位置设置为[max(position),架子= 1] + 1
并在其中放置position = [max(position)where rack = 2]到book4的初始位置(以缩小差距)
I need to move book4 to the end of shelf 1, therefore I need to set book4 position to [max(position) where shelf=1] + 1 and position where position=[max(position) where shelf=2] to book4 initial position (to close the gap)
我尝试了这个,但是Max似乎没有用方式...
I tried this, but Max doesn't seem to work this way...
Book.objects.filter(shelf=2).annotate(max_position_on_shelf=Max('position'))\
.filter(position=F('max_position_on_shelf'))\
.update(position=F('max_position_on_shelf') + 1)
推荐答案
更简单:
from django.db.models import Max
class Book(models.Model):
....
def move(self, shelf_num):
Book.objects.filter(shelf=self.shelf).order_by('-position')[:1].update(position=self.position)
self.position = Book.objects.filter(shelf=shelf_num).aggregate(Max('position')) + 1
self.save()
这篇关于Django ORM如何在查询中引用另一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文