Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top