Django QuerySet - 如何 "disable"以前的过滤值

标签 django model filter django-queryset

我有一个基础模型类,它在每次更改对象时创建对象的历史记录。该模型具有名为“is_history”的字段。这个想法是,每次有人更改模型时,都会使用旧数据创建模型的新实例。具有旧数据的新模型具有“is_history=True”,因为成为历史对象。 在默认的管理员更改列表中,我不想看到历史对象。默认情况下,我不想在任何地方看到它们。这就是为什么我创建了新的管理器来覆盖默认的 get_query_set() 并添加“is_history=False”。

def get_query_set(self):
    qs = super(ModelHistoryManager, self).get_query_set()
    return qs.filter(is_history=False)

但我也应该很少在更改 ListView 中显示历史对象,例如使用管理过滤器。

我的问题是:我有一个查询集已经过滤了这个值。但是在管理员的过滤器中,我从基本管理器中获取了过滤后的查询集,我想将此过滤器从 is_history=False 更改为 is_history=True,或者如果用户想要显示所有记录 - 历史记录,则删除“is_history”的过滤器和原始记录。

有什么想法吗?

最佳答案

让我引用关于 Custom Managers 的 django 文档:

If you use custom Manager objects, take note that the first Manager Django encounters (in the order in which they’re defined in the model) has a special status. Django interprets the first Manager defined in a class as the “default” Manager, and several parts of Django (including dumpdata) will use that Manager exclusively for that model. As a result, it’s a good idea to be careful in your choice of default manager in order to avoid a situation where overriding get_query_set() results in an inability to retrieve objects you’d like to work with.

所以,你应该这样做:

class MyModel(Model):
    objects = models.Manager() # The default manager.
    custom_manager = MyCustomManager() # This has overrided the get_query_set method

当然,如果你想要过滤的模型实例,你应该使用custom_manager而不是objects

关于Django QuerySet - 如何 "disable"以前的过滤值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18980965/

相关文章:

django - celery 减慢django

python - 使用正则表达式重定向 Django 中的页面?

python - 有人在做异步数据库提交吗?

JavaFX(带有 FXML)MVC : Model use Controller

javascript - 通过推送更新类型数组的 Backbone 模型属性

django 多态模型,过滤子类字段

django - 尝试在 django 模型中设置 BooleanField 值时出现奇怪的问题

android - 如何通过EditText过滤ListView

php - 过滤网页

javascript - javascript 中的参数销毁器