Django 批量更新两个表的数据
Django bulk update with data two tables over
我想批量更新 table 数据 table 两秒。对于文档中提到的更简单的情况已经给出了解决方案:
Entry.objects.update(headline=F('blog__name'))
有关该解决方案,请参阅
从示例扩展,假设 Entry
通过名为 blog
的字段具有对 Blog
的外键引用,并且 Blog
具有外键引用通过名为 author
的字段到 User
。我想要相当于:
Entry.objects.update(author_name=F('blog__author__username'))
与先前的解决方案一样,该解决方案预计将采用 SubQuery
和 OuterRef
。
我在这里问的原因是因为我对这个问题开始使用多个 OuterRef
缺乏信心,并且会混淆它指的是哪个外部引用。
The reason I ask here is because I lack confidence where this problem starts to employ multiple OuterRefs, and confusion arises about which outer ref it refers to.
它不需要多个外部引用,您可以更新为:
from django.db.models import OuterRef, Subquery
author_name = Author.objects.filter(
<b>blogs__id=OuterRef('blog_id')</b>
).values_list(
'username'
)[:1]
Entry.objects.update(
author_name=Subquery(author_name)
)
因此,您在此处指定要查找具有相关 Blog
且 id
等于 Entry
的 blog_id
的 Author
。
我想批量更新 table 数据 table 两秒。对于文档中提到的更简单的情况已经给出了解决方案:
Entry.objects.update(headline=F('blog__name'))
有关该解决方案,请参阅
从示例扩展,假设 Entry
通过名为 blog
的字段具有对 Blog
的外键引用,并且 Blog
具有外键引用通过名为 author
的字段到 User
。我想要相当于:
Entry.objects.update(author_name=F('blog__author__username'))
与先前的解决方案一样,该解决方案预计将采用 SubQuery
和 OuterRef
。
我在这里问的原因是因为我对这个问题开始使用多个 OuterRef
缺乏信心,并且会混淆它指的是哪个外部引用。
The reason I ask here is because I lack confidence where this problem starts to employ multiple OuterRefs, and confusion arises about which outer ref it refers to.
它不需要多个外部引用,您可以更新为:
from django.db.models import OuterRef, Subquery
author_name = Author.objects.filter(
<b>blogs__id=OuterRef('blog_id')</b>
).values_list(
'username'
)[:1]
Entry.objects.update(
author_name=Subquery(author_name)
)
因此,您在此处指定要查找具有相关 Blog
且 id
等于 Entry
的 blog_id
的 Author
。