0

我有以下型号:

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编辑 a时Letter Version会创建一个新的。我正在尝试选择Letter最近使用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个字母的列表编辑吗?

4

1 回答 1

1

您可以annotate()使用Max()of letterversion__created,然后order_by()使用它们。

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]
于 2012-04-16T17:30:01.157 回答