gpt4 book ai didi

python - Django,在prefetch_related之后更新对象

转载 作者:太空狗 更新时间:2023-10-30 00:47:37 26 4
gpt4 key购买 nike

我有以下模型:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com