- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有以下模型:
class Publisher(models.Model):
name = models.CharField(max_length=30)
class Book(models.Model):
title = models.CharField(max_length=100)
publisher = models.ForeignKey(Publisher)
在我的 views.py 中,当我想显示出版商页面时,我也想显示他们的书,所以我通常会这样做:
publisher = Publisher.objects.prefetch_related('book_set').filter(pk=id).first()
然后,经过一些处理后,我还对书籍进行了一些处理
for book in publisher.book_set.all():
foo()
效果很好,但我有一个问题。如果在查询和 for 循环之间添加了一本书,publisher.book_set.all()
将不会有新添加的书籍,因为它已被预取。
有没有办法更新发布者对象?
最佳答案
您可以删除实例上的整个预取缓存:
if hasattr(publisher, '_prefetched_objects_cache'):
del publisher._prefetched_objects_cache
如果您只想删除特定的预取关系:
if hasattr(publisher, '_prefetched_objects_cache'):
publisher._prefetched_objects_cache.pop('book_set', None)
关于python - Django,在prefetch_related之后更新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48109318/
我有一个问题,我现在想解决一天。 随着模型 class Quote(models.Model): text = models.TextField() source = models.F
我有一个 Django 网站,模型为 Event ,让我们说: class Event(models.Model): home = models.ForeignKey('Team', rela
我现在正在构建一个基本的时间记录应用程序,我有一个使用 django-taggit 的 todo 模型。我的 Todo 模型如下所示: class Todo(models.Model): pr
我需要列出我所有的设备。为此,我使用与减少查询量相关的预取。但是其中一个花费了太多时间..我想知道它是否不能更好。 我将从模型构造开始:我想要一个设备列表。 class Device(models.M
我正在尝试优化我的查询,但 prefetch_related 坚持加入表并选择所有字段,即使我只需要关系表中的 id 列表。 您可以忽略第四个查询。它与问题无关。 相关代码: class Contac
在 Django docs 中给出这些模型: class Topping(models.Model): name = models.CharField(max_length=30) class
我有 Menu具有与自身相关的名为 parent 的 ForeignKey 的模型。 如果 parent 为 None 则表示此菜单是父菜单,如果它显示另一个 Menu 对象,则表示它是其父级的子菜单
我正在尝试使用 PersonScore 对这 3 个表进行内部联接,但找不到 persontype。我究竟做错了什么? 楷模: class PersonScore(models.Model):
我有这样的模型 Model Trip: hotel: m2m_field to Hotel flight: m2m_field to Flight Model Hotel: city: f
我有两个 Django 模型: class Product(models.Model): name = models.CharField(max_length=80, null=True)
如果我的模型看起来像: class Publisher(models.Model): pass class Book(models.Model): publisher = models
我已经在 django 1.4 中从主干尝试过 prefetch_related(),但无法预取反向查找。 我的简化模型(每本书有很多价格): class Book(models.Model):
我几乎可以肯定我在这里做错了什么,但我想不通。 在我的应用程序中,项目可以存储在工作区中,如下所示: # models.py class Item(models.Model): name
我正在开发一个 Django 网络应用程序,我正在使用 prefetch_related 和 select_related 方法来最小化单个数据库的访问量,我在我的 User 模型中有一个特定的方法可
我正在使用 DRF 序列化一些相关模型。在我下面的玩具示例中,假设每个作者都可以拥有一百万本书。显然对所有“好”书进行数据库查询,然后对所有“坏”书进行另一个数据库查询是低效的。 这篇文章 [ htt
我想通过 prefetch_related 查询来获取我的模型和所有相关模型,遵循一对多关系,但具有过滤条件。我的目标是使用 prefetch_related 在一个 django 查询中获取我的所有
我正在尝试返回,对于每个 UserProfile,它具有一对多 Subscription,它具有两个 Artist 的外键> 和 UserProfile,每个艺术家有许多 ReleaseGroup,c
我有一个关系简单的模型 class Tasks(models.Model): initiator = models.ForeignKey(User, on_delete = models.CAS
我已经用 GET 实现了一个基于类的 View 获取工资单详情的方法 id .我如何附加 net_allowance在工资单中 object所以JSON看起来像这样: { "employee_
我以前使用过 select_related 和 prefetch_related,效果很好。 我正在处理一个当前项目,由于某种原因,我无法弄清楚为什么我的预取相关查询无法正常工作,因此我收到了很多冗余
我是一名优秀的程序员,十分优秀!