Skip to content

Instantly share code, notes, and snippets.

@XiaonuoGantan
Created June 4, 2014 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XiaonuoGantan/ed8610cffee8f68a4164 to your computer and use it in GitHub Desktop.
Save XiaonuoGantan/ed8610cffee8f68a4164 to your computer and use it in GitHub Desktop.
Many-to-Many relationship with composite keys in tables
import os
from sqlalchemy import Column, DateTime, String, Integer, ForeignKey, func, ForeignKeyConstraint
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Department(Base):
__tablename__ = 'department'
id = Column(Integer, primary_key=True)
country_id = Column(Integer, primary_key=True)
name = Column(String)
employees = relationship(
'Employee',
secondary='department_employee_link'
)
class Employee(Base):
__tablename__ = 'employee'
id = Column(Integer, primary_key=True)
name = Column(String)
hired_on = Column(DateTime, default=func.now())
departments = relationship(
Department,
secondary='department_employee_link'
)
class DepartmentEmployeeLink(Base):
__tablename__ = 'department_employee_link'
department_id = Column(Integer)
department_country_id = Column(Integer)
employee_id = Column(Integer, ForeignKey('employee.id'), primary_key=True)
__table_args__ = (
ForeignKeyConstraint(
[department_id, department_country_id],
[Department.id, Department.country_id]
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment