【问题标题】:Django query, annotate latest childs valueDjango查询,注释最新的childs值
【发布时间】:2017-06-19 13:42:38
【问题描述】:

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

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

我需要类似的东西:

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

谢谢!

【问题讨论】:

  • 你想达到什么目的? last() 只返回一个对象,annotate 只能通过一个 QuerySet。
  • 'StoreItem' 例如有 10 个“运动”,我只需要最后一个运动的值 total_count 所以如果:StoreItem.objects.last().movements.last().total_count => 32 然后当我像 store_items = StoreItem.objects.annotate(total_count_of_last_movement=...??...) 那样注释它时stole_items.last().total_count_of_last_movement => 32...??... 中必须包含的内容。谢谢你这么快的回复! :)

标签: django annotate


【解决方案1】:

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

假设您的模型类似于:

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

希望这会有所帮助。

【讨论】:

  • 谢谢!这对我来说是新事物:)
  • 很高兴它有帮助。
【解决方案2】:

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

既然你想要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

希望这会有所帮助,如果没有,请指定您的模型以及最后您想要得到什么。

【讨论】:

  • 我试图进行一个查询,它给了我对象列表 StoreItem ,对象将具有表 'store_itrems'(id, title, ect.) 中的所有属性和一个“附加”属性 - some_value_of_last_movement,取 StoreItem 对象最后一次移动的值。是否可以使用annotate。谢谢。
猜你喜欢
  • 2021-05-09
  • 2017-04-07
  • 2011-04-08
  • 1970-01-01
  • 1970-01-01
  • 2020-01-18
  • 2013-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多