Django查询,注释最新的childs值
是否可以注释最后一个子项的值?有一个模型StoreItem,它与模型移动有许多关系:Django查询,注释最新的childs值,django,annotate,Django,Annotate,是否可以注释最后一个子项的值?有一个模型StoreItem,它与模型移动有许多关系: StoreItem.objects.last().movements.last().total_count # => 32 我需要像这样的东西: StoreItem.objects.annotate(total_count_of_last_movement=...??...) class Movement(models.Model): ... store_item = models.F
StoreItem.objects.last().movements.last().total_count # => 32
我需要像这样的东西:
StoreItem.objects.annotate(total_count_of_last_movement=...??...)
class Movement(models.Model):
...
store_item = models.ForeignKey(StoreItem, ..., related_name='movements')
total_count = models.IntegerField(...)
class StoreItem(models.Model):
...
title = models.TextField(...)
谢谢大家! 我不完全理解你的问题,但我的建议是: 由于需要设置
StoreItem
,您可以尝试:
last_movement_total_count = StoreItem.objects.last().movements.last().total_count
然后:
在这里,store\u items\u with\u count
保存所有StoreItems
,其中至少有一个movement
的total\u count
值为last\u movement\u total\u count
,然后
store_items_with_count.last() # the last StoreItem
但是,如果您想要上一个移动的StoreItem
,它更简单:
last_store_item = Movement.objects.last().store_item
希望这对您有所帮助,如果没有,请指定您的型号以及您希望在最后得到什么。给出您的最后评论,您无需汇总 假设您的模型类似于:
StoreItem.objects.annotate(total_count_of_last_movement=...??...)
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
希望这能有所帮助。您希望实现什么目标
last()
仅返回一个对象,您可以仅对查询集进行注释。'StoreItem'例如有10个'Movement',我只需要最后一次移动的值total_count
所以如果:StoreItem.objects.last().movements.last().total_count
=>32
然后当我像store_items=StoreItem.objects.annotate(total_count_of u last_movement=.??…)
然后偷走了_items.last().total_count_of u last_movement
=>32
。中必须包含的内容…?
。谢谢你这么快的回复!:)我试图进行一个查询,它给出了对象列表StoreItem
,对象将具有表“store\u itrems”(id、title等)中的所有属性和一个“附加”属性-最后一次移动的一些值,它获取StoreItem对象最后一次移动的值。是否可以使用注释。谢谢,谢谢!这对我来说是一件新鲜事:)很高兴它有帮助。