Django可以在模型中延迟加载字段吗? [英] Can django lazy-load fields in a model?

查看:116
本文介绍了Django可以在模型中延迟加载字段吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的django模型中有一个很大的 TextField ,我通常不需要使用它。有没有办法告诉Django延迟加载此字段?即除非我明确要求,否则不要麻烦从数据库中拉出它。每次我引用这些对象时,我都在浪费大量内存和带宽将 TextField 拖入python。

One of my django models has a large TextField which I often don't need to use. Is there a way to tell django to "lazy-load" this field? i.e. not to bother pulling it from the database unless I explicitly ask for it. I'm wasting a lot of memory and bandwidth pulling this TextField into python every time I refer to these objects.

另一种方法是为该字段的内容创建一个新表,但是如果可以的话,我宁愿避免这种复杂性。

The alternative would be to create a new table for the contents of this field, but I'd rather avoid that complexity if I can.

推荐答案

使用 defer()语句而不是模型定义进行查询时,功能会发生。在文档中查看:
http:// docs.djangoproject.com/en/dev/ref/models/querysets/#defer

The functionality happens when you make the query, using the defer() statement, instead of in the model definition. Check it out here in the docs: http://docs.djangoproject.com/en/dev/ref/models/querysets/#defer

现在,实际上,您是重构和提取数据的替代解决方案放入另一个表是一个非常好的解决方案。有人会说需要延迟加载字段意味着存在设计缺陷,并且应该对数据进行不同的建模。

Now, actually, your alternative solution of refactoring and pulling the data into another table is a really good solution. Some people would say that the need to lazy load fields means there is a design flaw, and the data should have been modeled differently.

无论哪种方法都可以!

Either way works, though!

这篇关于Django可以在模型中延迟加载字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆