Django的。具有有限集合域的代理模型 [英] Django. Proxy model with limited set of fields

查看:144
本文介绍了Django的。具有有限集合域的代理模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

主要时刻 - 数据库方案不是从头开始设计的。它是从遗留系统继承而来的,现在必须保持原样,因为它也与一些外部系统共享。所以我们有一种:

  class A(models.Model):

列表的110个字段

field_1 = models.CharField()
字段_... = models.CharField()
field_n = models.CharField()
有没有什么办法可以使用模型B,这将是代理模型,并且将有一些有限的字段?



<



喜欢:

  class B(A):
class Meta:
proxy = True
field_3 = models.CharField()
field_5 = models.CharField()
field_10 = models.CharField()

目前唯一的解决方案是创建一些非托管模型。但是代理模型看起来更好的这个目标..或者不是?

解决方案

根据 docs ,代理模型不是您要查找的


所以,一般规则是:



如果您镜像现有的模型或数据库表, t
想要所有的原始数据库表列,使用Meta.managed = False。
该选项通常用于建模数据库视图和表
不受Django控制。



如果您想要更改模型的
仅Python行为,但保留与原始资源
中的所有相同的字段,请使用Meta.proxy = TRUE。这样做会使得
代理模型是保存原始
模型的存储结构的精确副本。


您最好的打算是在SQL中创建一个视图,只列出您想要的字段,然后使用非托管表连接到该视图。


Main moment - database scheme is not designed from scratch. It's inherited from legacy system and must be left as is at the moment, because it's also shared with some external systems. So we have kind of:

class A(models.Model): 
    """
    List of 110 fields
    """
    field_1 = models.CharField()
    field_... = models.CharField()
    field_n = models.CharField()

Are there any way to have model B, which will be proxy model and will have limited set of fields?

Like:

class B(A):
    class Meta: 
        proxy = True
    field_3 = models.CharField()
    field_5 = models.CharField()
    field_10 = models.CharField()

The only solution, that I have in mind currently - create some unmanaged models. But proxy models look better for this goal.. or not?

解决方案

According to the docs, proxy model isn't what you are looking for

So, the general rules are:

If you are mirroring an existing model or database table and don’t want all the original database table columns, use Meta.managed=False. That option is normally useful for modeling database views and tables not under the control of Django.

If you are wanting to change the Python-only behavior of a model, but keep all the same fields as in the original, use Meta.proxy=True. This sets things up so that the proxy model is an exact copy of t he storage structure of the original model when data is saved.

Your best bet is to create a view in SQL listing only the fields that you want and then use an unmanaged table to connect to it.

这篇关于Django的。具有有限集合域的代理模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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