简体   繁体   English

Django不可变模型查询

[英]Django immutable model query

I'm looking at a state isolation / read-only situation in Django (1.6) and i'm looking for a method to make a query return objects that are immutable. 我正在寻找Django(1.6)中的状态隔离/只读情况,并且正在寻找一种方法来使查询返回不可变的对象。

I'm looking to fit something like the following wrapping the usual db atomicity api 我正在寻找适合以下包装常规数据库原子性API的内容

MyModel.objects.filter(foo="bar").all(read_only=True)

My current thinking is this will be a custom Manager, but i'd potentially like something that can be added at runtime like: 我当前的想法是,这将是一个自定义管理器,但是我可能希望可以在运行时添加以下内容:

read_only(MyModel.objects.filter(foo="bar").all())

Without too much voodoo or making them unmanaged (the option to throw an Exception on state change would be good). 如果没有太多的伏都教或不对其进行管理(选择在状态更改时引发Exception的选项会很好)。

The key thing is that the Model supports both read-only and the default read-write query type ideally with changes limited to code that is required to be read-only. 关键是,模型理想地支持只读和默认的读写查询类型,并且更改仅限于要求只读的代码。

My other option is something like: 我的其他选择是这样的:

with isolation(raise_exception=True):
    m = MyModel.objects.get(id=foo)
    m.do_unknown_thing_that_may_mutate()

Are there existing solutions I'm missing at a higher level than the database? 是否存在比数据库更高级别缺少的现有解决方案?

One possibility might be to define a proxy class which overrides save to be a no-op: 一种可能是定义一个save覆盖为no-op的代理类:

class MyReadOnlyModel(MyModel):
    def save(self, *args, **kwargs):
        pass
    class Meta:
        proxy = True

Then just query MyReadOnlyModel instead of MyModel. 然后只需查询MyReadOnlyModel而不是MyModel。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM