views:

116

answers:

1

I've come across a place in my current project where I have created several classes for storing a complicated data structure in memory and a completed SQL schema for storing the same data in a database. I've decided to use SQLAlchemy as an ORM layer as it seems the most flexible solution that I can tailor to my needs.

My problem is that I now need to map an entire table to just an array attribute in memory and am struggling to find out if this is possible and, if it is, how to do it with SQLAlchemy. It is still possible for me to change the data structures in code (although less than ideal) if not, but I would prefer not to.

The table in question is created using the following SQL:

CREATE TABLE `works` (
 `id` BIGINT NOT NULL auto_increment,
 `uniform_title` VARCHAR(255) NOT NULL,
 `created_date` DATE NOT NULL,
 `context` TEXT,
 `distinguishing_characteristics` TEXT,
 PRIMARY KEY (`id`),
 INDEX (`uniform_title` ASC),
 INDEX (`uniform_title` DESC)
) ENGINE = InnoDB DEFAULT CHARSET = utf8 ;

CREATE TABLE `variant_work_titles` (
 `id` BIGINT NOT NULL auto_increment,
 `work_id` BIGINT NOT NULL,
 `title` VARCHAR(255) NOT NULL,
 PRIMARY KEY(`id`),
 INDEX (`work_id`),
 INDEX (`title` ASC),
 INDEX (`title` DESC),
 FOREIGN KEY (`work_id`)
  REFERENCES `works` (`id`)
  ON DELETE CASCADE
  ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;

This is just a small part of the complete database and the same thing is going to be required in several places.

+1  A: 

It seems you want something like

work_instance.variants = [<some iterable of variants>]

If not please clarify in your question.

Ideally you should have 2 mappings to these 2 tables. It doesn't matter if you won't access the second mapping anywhere else. work mapping should have a one-to-many relationship to variant mapping. This would give you a list of variant instances associated with a particular work on whichever attribute you define your relationship.

muhuk
That sounds pretty much like what I want. Is there a way to do that without having to have a python class specifically for the variants? Or should I give in and have a class for each of these elements despite their simplicity?
workmad3
You don't NEED a class for SQLAlchemy ORM. You can just query a table without an ORM mapping. You can use an explicit fetchall() get all the rows; you get a list of dictionaries.
S.Lott
S.Lott is right, you don't have to have a class for each table. But I would create them anyways. Somewhere in your code you'll want to operate on variants and you might just find it more practical to have the mapping than to attach the functionality on work mapping.
muhuk
I've gone for a (completely restructured) model with classes for variants (created using elixir) in the end, but the end-result was what muhuk described.
workmad3