我有以下型号:
class Item(models.Model):
closed = models.DateTimeField(blank=True, null=True)
closed_by = models.ForeignKey(User, blank=True, null=True)
class Letter(models.Model):
item = models.ForeignKey(Item)
created = models.DateTimeField(default=datetime.now)
letter_name = models.CharField(max_length=40)
file_name = models.CharField(max_length=40, blank=True, null=True)
deleted = models.DateTimeField(blank=True, null=True)
deleted_by = models.ForeignKey(User, blank=True, null=True)
def lastVersion(self):
return self.letterversion_set.order_by('created').latest().created
class LetterVersion(models.Model):
letter = models.ForeignKey(Letter)
created = models.DateTimeField(default=datetime.now)
created_by = models.ForeignKey(User)
text = models.TextField()
def letterItem(self):
return self.letter.item
编辑Letter
时,会创建新的Letter Version
。我正在尝试使用Letter
选择最近编辑过的最近3个LetterVersion.create
。我的views.py
:
lettersAll = Letter.objects.filter(item=i_iID,deleted__isnull=True).order_by('-letterversion__created')[:3]
不幸的是,即使它们来自同一个LetterVersion
,这也会让我获得基于其创建日期/时间的最后3 Letter
。
letter 1 version 3 [1]
letter 3 version 4 [2]
letter 1 version 2 [3]
letter 1 version 1
letter 2 version 2
letter 2 version 1
letter 3 version 3
letter 3 version 2
letter 3 version 1
我想要的地方:
letter 1 version 3 [1]
letter 3 version 4 [2]
letter 2 version 2 [3]
无论如何,我可以获得编辑的最后3个字母的列表吗?
答案 0 :(得分:1)
您可annotate()
Max()
letterversion__created
,然后order_by()
。{/ p>
from django.db.models import Max
lettersAll = Letter.objects.filter(
item=i_iID,
deleted__isnull=True
).annotate(
last_created_version=Max('letterversion_created')
).order_by('-last_created_version')[:3]