Question

This question essentially two parts. 1. I have a situation where I require things to be unique together i.e the elements in db need to be unique together with each other.

Lets say we have a model Things ( Rough PseudoCode)

Class ShoppingList( object ):
     thing1_id = Column(Integer)
     thing2_id = Column(Integer)

Now I need thing1_id and thing2_id to be a unique together ie the set of thing1_id and thing2_id needs to be unique together. Coming from django world I know that you can do a meta declaration in django models of unique_together. But how can do this in turbogears .

  1. Also how do I actually apply a unique_together on a legacy system.
Was it helpful?

Solution 2

  1. For the first part of your question, if I understand your question correctly, I believe you are talking about the need for defining composite primary keys. As stated in http://docs.sqlalchemy.org/en/latest/core/schema.html#describing-databases-with-metadata:

    Multiple columns may be assigned the primary_key=True flag which denotes a multi-column primary key, known as a composite primary key.

    Defining such a relationship on a class using the declarative ORM way in SQLAlchemy, should be as simple as:

    class ShoppingList(Base):
        thing1_id = Column(Integer, primary_key=True)
        thing2_id = Column(Integer, primary_key=True)
    
  2. As for the second part of your question, I believe you mean how one would define the same SQLAlchemy mapping for an existing, legacy database. If so, you should be able to use the above approach, just don't create the database from the ORM definition. You may also use the classic mapping way, described in: http://docs.sqlalchemy.org/en/rel_0_8/orm/mapper_config.html?highlight=composite%20primary%20key#classical-mappings

OTHER TIPS

You simply want to add a UniqueConstraint to your table definition (using a primary key would achive similar effects, but with different semantics nevertheless).

This is as simple as:

Class ShoppingList( object ):
    thing1_id = Column(Integer)
    thing2_id = Column(Integer)

    __table_args__ = (
        UniqueConstraint('thing1_id', 'thing2_id'),
    )

See also https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/table_config.html#table-configuration

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