简体   繁体   English

Django中的模型和数据库视图

[英]Models and database views in django

I'm setting up django models for a database, and currently my approach is to directly map database tables to Models. 我正在为数据库设置django模型,当前我的方法是直接将数据库表映射到Models。 However, in some cases I actually need to work with a relatively complicated view. 但是,在某些情况下,我实际上需要使用相对复杂的视图。 A specific case is where I have a table (in a report, not database) which needs to show a merged list from related database tables: 一种特殊情况是我有一个表(在报表中,而不是数据库中),该表需要显示相关数据库表中的合并列表:

class Entity(Models):
    name = CharField()

class LargeEntity(Entity):
    size = FloatField()

class SmallEntity(Entity):
    type = ForeignKey(SmallEntityType)

The report (and form) needs to show: 报告(和表格)需要显示:

Entity name - entity.name
Large/Small - 'Large' if entity is LargeEntity else 'Small'
size/type   - entity.size if entity is LargeEntity else 'type'

This can be done through CASE statements in SQL, but since this happens quite a lot in my data, I would rather find a neater solution. 这可以通过SQL中的CASE语句完成,但是由于这种情况在我的数据中经常发生,所以我宁愿找到一个更整洁的解决方案。

Changing the report format is not on option, but the database can be changed if there is a better way of implementing this. 不能选择更改报告格式,但是如果有更好的实现方法,则可以更改数据库。

In case if each entity type does not contain a lot of attributes, you can create one model with all required fields and one or more fields in that model to distinguish entities from each other by types or something else: 如果每种实体类型不包含很多属性,则可以创建一个具有所有必填字段的模型,并在该模型中创建一个或多个字段,以按类型或其他方式将实体彼此区分开:

class Entity(Models):
    NORMAL, LARGE, SMALL = 0, 1, 2
    ETYPE = (
        (NORMAL, 'Normal'),
        (LARGE, 'Large'),
        (SMALL, 'Small'),
    )
    entity_type = IntegerField(choices=ETYPE,...)

    name = CharField()
    size = FloatField()
    smalltype = ForeignKey(SmallEntityType)
    ...

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

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