问题描述
我有 2 个模型 Parent
,Child
class Parent(models.Model):
id = Base64UUIDField(primary_key=True,editable=False)
cost = models.DateTimeField(default=None,blank=True,null=True)
class Child(models.Model):
id = Base64UUIDField(primary_key=True,null=True)
parent = models.ForeignKey(Parent,related_name= "children",related_query_name= "child")
我需要将 cost
对象的 Parent
列填充到该父项的所有子项的最大成本
我尝试对新列 new_cost
及其作品进行注释。
parents.annotate(new_cost=Max('child__cost'))
但我需要将值填充到现有列 cost
。试过这样的东西,但没有用。
parents.update(cost=Max('child__cost'))
解决方法
可能可以通过 Subquery
expression 实现:
from tkinter import *
def click_me():
print(i.get())
root =Tk()
i=IntVar()
c = Checkbutton(root,text = "Python",variable=i)
c.pack()
b = Button(root,text="Click here",command=click_me)
b.pack()
root.geometry("400x400+120+120")
root.mainloop()
不过,当您需要相关 from django.db.models import OuterRef,Subquery
Parent.objects.update(
cost=Subquery(Child.objects.filter(
parent_id=OuterRef('pk')
).values('cost').order_by('-cost')[:1])
)
的最大成本时,我建议您只使用 .annotate(…)
。
使用aggregate
反对annotate
test = parents.aggregate(new_cost=Max('child__cost'))
parents.update(cost=test["new_cost"])