Created
June 4, 2014 18:05
-
-
Save XiaonuoGantan/ed8610cffee8f68a4164 to your computer and use it in GitHub Desktop.
Many-to-Many relationship with composite keys in tables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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