I would like to create an association between a Dataset object and all Category objects through the Annotation table.
A Dataset contains a collection of Annotations. Each Annotation has a single Category. I want Dataset.categories to contain the unique set of Categories made up of all the Categories of all the Annotations in that Dataset instance. I have tried doing this with a double association table (dataset_categories), but it is not working. What is the right way to do this? Here is my code so far:
Base = declarative_base()
dataset_categories = Table('dataset_categories', Base.metadata,
Column('dataset_id', Integer, ForeignKey('datasets.id')),
Column('annotation_id', Integer, ForeignKey('annotations.id')),
Column('category_id', Integer, ForeignKey('categories.id')))
class Dataset(Base):
__tablename__ = 'datasets'
id = Column(Integer, primary_key=True)
annotations = relationship("Annotation")
categories = relationship("Category", secondary=dataset_categories)
class Annotation(Base):
__tablename__ = 'annotations'
id = Column(Integer, primary_key=True)
category_id = Column(Integer, ForeignKey('categories.id'), nullable=False)
category = relationship("Category")
dataset_id = Column(Integer, ForeignKey('datasets.id'))
class Category(Base):
__tablename__ = 'categories'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False, unique=True)
dataset = relationship("Dataset", secondary=dataset_categories)
dataset_id = Column(Integer, ForeignKey('datasets.id'),
back_populates='categories')
Without the requirement that the association contain only the unique categories this would be as simple as using an association_proxy. One option is to define the collection class to use as set when defining the relationship:
class Dataset(Base):
__tablename__ = 'datasets'
id = Column(Integer, primary_key=True)
annotations = relationship("Annotation")
categories = relationship("Category", secondary="annotations", collection_class=set)
On the other hand the secondary table of a relationship does not have to be a base table, and so a simple select from annotations can be used:
class Dataset(Base):
__tablename__ = 'datasets'
id = Column(Integer, primary_key=True)
annotations = relationship("Annotation")
categories = relationship("Category",
secondary="""select([annotations.c.dataset_id,
annotations.c.category_id]).\\
distinct().\\
alias()""",
viewonly=True)
Related
The example given in sqlalchemy documentation is,
from sqlalchemy import Integer, ForeignKey, String, Column
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
class Customer(Base):
__tablename__ = 'customer'
id = Column(Integer, primary_key=True)
name = Column(String)
billing_address_id = Column(Integer, ForeignKey("address.id"))
shipping_address_id = Column(Integer, ForeignKey("address.id"))
billing_address = relationship("Address", foreign_keys=[billing_address_id])
shipping_address = relationship("Address", foreign_keys=[shipping_address_id])
class Address(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key=True)
street = Column(String)
city = Column(String)
state = Column(String)
zip = Column(String)
I am trying a similar example (cannot place so much code here) it does not work if I do something similar to this:
from sqlalchemy import Integer, ForeignKey, String, Column
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
class Customer(Base):
__tablename__ = 'customer'
id = Column(Integer, primary_key=True)
name = Column(String)
billing_address_id = Column(Integer, ForeignKey("address.id"))
shipping_address_id = Column(Integer, ForeignKey("address.id"))
billing_address = relationship("Address", foreign_keys=[billing_address_id], back_populates('bill_addr'))
shipping_address = relationship("Address", foreign_keys=[shipping_address_id], back_populates('ship_addr'))
class Address(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key=True)
street = Column(String)
city = Column(String)
state = Column(String)
zip = Column(String)
bill_addr = relationship("Customer", back_populates('billing_address'))
ship_addr = relationship("Customer", back_populates('shipping_address'))
I have two doubts:
Q1) Is the above relationship bidirectional?
Q2) How to establish a bidirectional relationship between tables with multiple join paths?
edit:
In my case I am getting the following error:
sqlalchemy.exc.AmbiguousForeignKeysError
sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables
on relationship User.expenses - there are multiple foreign key paths linking the tables.
Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a
foreign key reference to the parent table.
It is working if I used 'backref' instead of 'back_populates'. I placed the 'backref' in the relationships on the side where both the foreign keys are present and removed the relationships on the other table.
How can i do a foreign key refer to id to multiple tables?
class HistoryActivation(Base):
__tablename__ = 'active_control'
id = Column(Integer, primary_key=True)
id_entity = Column(Integer) #This one refer to any entity (id) that has a relation with this class.
date = Column(DATE)
user = Column(String(120))
active = Column(BOOLEAN)
class Person(Base):
__tablename__ = 'persons'
id = Column(Integer, primary_key=True)
name = Column(String(50))
history_activation = relationship("HistoryActivation",
primaryjoin="HistoryActivation.id_entidade == Person.id")
class Company(Base):
__tablename__ = 'companies'
id = Column(Integer, primary_key=True)
name = Column(String(50))
history_activation = relationship("HistoryActivation",
primaryjoin="HistoryActivation.id_entidade == Company.id")
class Whatever(Base): ...
So, id_entity refer to id to various tables, something like:
id_entity = Column(Integer, ForeignKey('Person.id or Company.id or Whatever.id').
Is possible to tell ForeignKey can refer more than one relation?
I have an existing set of sqlalchemy models like so
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String)
first_name = Column(String)
last_name = Column(String)
email = Column(String)
user_group = Table('user_group', Base.metadata,
Column('user_id', Integer, ForeignKey('users.id')),
Column('group_id', Integer, ForeignKey('groups.id'))
)
class Group(Base):
__tablename__ = 'groups'
id = Column(Integer, primary_key=True)
name = Column(String)
members = relationship("User", secondary=user_group)
and I would like to create a third model which can have a 1 to many relationship with either a User or a Group type. So I want to end up with something that can be used like this
class Contact(Base):
__tablename__ = 'contacts'
id = Column(Integer, primary_key=True)
type_id = Column(Integer) # the id of the group or user row which it refers to.
type = Column(String) # 'group' or 'user'
class Thing(Base):
__tablename__ = 'things'
relationship('Contact') # Array of Contacts
where
thing = Thing()
thing.contacts[0].type # returns 'group' or 'user'
thing.contacts[0].contact # returns the actual User or Group object
I know this can be done with inheritance but is there any alternative? I'd rather not have to subclass my basic User and Group models.
Thanks in advance!
Read Generic Associations section of the documentation.
Your description matches the case of the Generic ForeignKey
I'm struggling with creating a database model for my Flask application.
Let's consider I have few product types and due to nature of my application I want to have separate tables for each product, while keeping generic properties in a common table:
Example:
products table
id type name price
1 'motorcycle' 'Harley' 10000.00
2 'book' 'Bible' 9.99
motorcycles table
id manufacturer model max_speed
1 'Harley-Davidson' 'Night Rod Special' 150
books table
id author pages
2 'Some random dude' 666
Things to consider:
all tables have one-to-one relationship
having motorcycle_id, book_id, etc_id in products table is not an option
having product_id in product tables is acceptable
two-way relationship
How can I declare such a relationship?
You are looking for joined table inheritance. The base class and each subclass each create their own table, each subclass has a foreign key primary key pointing to the base table. SQLAlchemy will automatically handle the joining whether you query the base or sub class.
Here is a working example for some products:
from decimal import Decimal
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Numeric
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///:memory:', echo=True)
session = sessionmaker(bind=engine)()
Base = declarative_base(bind=engine)
class Product(Base):
__tablename__ = 'product'
id = Column(Integer, primary_key=True)
type = Column(String, nullable=False)
name = Column(String, nullable=False, default='')
price = Column(Numeric(7, 2), nullable=False, default=Decimal(0.0))
__mapper_args__ = {
'polymorphic_on': type, # subclasses will each have a unique type
}
class Motorcycle(Product):
__tablename__ = 'motorcycle'
# id is still primary key, but also foreign key to base class
id = Column(Integer, ForeignKey(Product.id), primary_key=True)
manufacturer = Column(String, nullable=False, default='')
model = Column(String, nullable=False, default='')
max_speed = Column(Integer, nullable=False, default=0)
__mapper_args__ = {
'polymorphic_identity': 'motorcycle', # unique type for subclass
}
class Book(Product):
__tablename__ = 'book'
id = Column(Integer, ForeignKey(Product.id), primary_key=True)
author = Column(String, nullable=False, default='')
pages = Column(Integer, nullable=False, default=0)
__mapper_args__ = {
'polymorphic_identity': 'book',
}
Base.metadata.create_all()
# insert some products
session.add(Book())
session.add(Motorcycle())
session.commit()
print(session.query(Product).count()) # 2 products
print(session.query(Book).count()) # 1 book
I would like to have a one to many relation between two ORM objects and extend this with a second relation that links to the same 'many' object while applying a constraint.
The following example may elaborate:
class Users(SQLABase):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
addresses = relationship('Addresses', backref='user')
class Addresses(SQLABase):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
historic = (String(1))
add1 = Column(String)
user = Column(Integer, ForeignKey('users.id'))
I would like an attribute 'Users.valid_addresses' that relates to the same 'addresses' table filtering where Addresses.historic == 'N' like the following query:
Session.Query(Addresses).filter_by(historic = 'N').all()
I'm looking for the "SQLAlchemy way".
Can I apply a condition to a relation?
Am I expected to iterate over the results of the current relation?
Should I create an additional 'valid_addresses' object based on an SQL
view of the addresses table applying the condition?
I have the feeling this has already been answered but I'm failing to phrase the question correctly.
This is covered in the SQLAlchemy docs under "Specifying Alternate Join Conditions".
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String)
boston_addresses = relationship("Address",
primaryjoin="and_(User.id==Address.user_id, "
"Address.city=='Boston')")
class Address(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('user.id'))
street = Column(String)
city = Column(String)
state = Column(String)
zip = Column(String)