Django 查询,注释最新的子值

Django query, annotate latest childs value

是否可以注释最后一个子项的值?有模型 StoreItem,与模型 Movement 有很多关系:

StoreItem.objects.last().movements.last().total_count # => 32

我需要这样的东西:

StoreItem.objects.annotate(total_count_of_last_movement=...??...)

谢谢!

我不完全理解你的问题,但这是我的建议:

既然你想要StoreItem组,你可以试试:

last_movement_total_count = StoreItem.objects.last().movements.last().total_count

然后:

store_items_with_count = StoreItem.objects.filter(movement__total_count=last_movement_total_count)

此处,store_items_with_count 包含所有 StoreItems,其中至少一个 movementtotal_count 值为 last_movement_total_count,然后

store_items_with_count.last() # the last StoreItem

但是,如果你想要最后一个乐章的StoreItem,那就更简单了:

last_store_item = Movement.objects.last().store_item

希望对你有帮助,如果没有,请说明你的型号,最后你想得到什么。

鉴于您最后的评论,您不需要汇总。

假设您的模型是这样的:

class Movement(models.Model):
    ...
    store_item = models.ForeignKey(StoreItem, ..., related_name='movements')
    total_count = models.IntegerField(...)

class StoreItem(models.Model):
    ...
    title = models.TextField(...)

您只需要向 StoreItem 模型添加一个属性:

class StoreItem(models.Model):
    ...
    title = models.TextField(...)

    @property
    def last_movement_total_count(self):
        if self.movements is not None and self.movements.count() > 0:
            return self.movements.last().total_count
        return None # or -1 or something that tells that there are no movements

你可以这样做:

store_item = StoreItem.objects.last() # or get or whatever you need
last_movement_total_count = store_item.last_movement_total_count

希望这对您有所帮助。