简体   繁体   中英

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. 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.

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)
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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