开发者

SQLAlchemy query

I'm working on a web app and an db which deals with the following entities: computers, computer containers (computer_sets) and rules. It a firewall management tool. I'm having some troubles dealing with computer objects, because those computers stored within a computer_set are not the same objects as those computers not contained within a computer_set: a stand-alone computer can be in a rule, but a computer_set comput开发者_如何学Goer cannot be in a rule, i.e, only the container is allowed to be in a rule (I know I know, this is a mess, but I didn't create the firewall, I'm just programming a management tool :).

I created a DB (with SQLite) and I'm using SQLAlchemy. Thus, I created the classes Computer, ComputerSet, ComputerSetComputer and Rule and the corresponding tables . Now, in my application, I need to list all those computer objects. However, when I query the computers table, I get Computer objects and when I query my computerset_computers table, I get ComputerSetComputer objects. I would like to get a query object containing all my computers no matter whether or not they belong to a computer set. This way, I would be able to slice the query object and do pagination. Any ideas? I could change my DB design, though I cannot change the underlying concepts of a Computer, a Rule, .etc.

Thanks for your time, gsandorx :)


I see two ways to solve this problem: use union in low-level queries or use inheritance in model definition. I think the later is more convenient, since you get model objects from queries. Assuming you have ComputerBase abstract class and two its subclassess Computer and ComputerSetComputer, session.query(ComputerBase).all() will return the mixed list of all Computer and ComputerSetComputer objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜