【发布时间】:2020-12-06 23:15:21
【问题描述】:
https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_one/,
以 Django 的 Reporter/Article 作为我的实际问题的可比示例,我需要为我的查询集中的每个记者创建一篇新文章。
我现在的做法如下:
reporters = Reporter.objects.filter(...)
for reporter in reporters:
article = Article()
article.reporter = reporter
...
article.save()
问题是我有 25k 的“记者”,所以处理请求需要很长时间并引发超时。
我想知道是否有更好的方法,有点像:
Reporter.objects.filter(...).article_set.create(...)
【问题讨论】:
-
我最终保存了一个列表:
reporter_values = Reporter.objects.filter(...).values_list('id')然后使用列表理解,我在 python 中构建了每一篇文章:articles = [Article(reporter_id=value[0], ...) for value in reporter_values]并完成了所有内容:Article.objects.bulk_create(articles)这解决了问题第二,但是,如果有更好的方法来做到这一点,我很想知道。
标签: django django-models orm django-queryset crud