Relacje na kluczach złożonych za pomocą sqlalchemy
Mam ten prosty model książek autora i nie mogę znaleźć sposobu, aby imię i nazwisko i nazwisko były kluczem złożonym i używały go w relacji. Jakieś pomysły?
from sqlalchemy import create_engine, ForeignKey, Column, String, Integer
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine = create_engine('mssql://user:pass@library')
engine.echo = True
session = sessionmaker(engine)()
class Author(Base):
__tablename__ = 'authors'
firstName = Column(String(20), primary_key=True)
lastName = Column(String(20), primary_key=True)
books = relationship('Book', backref='author')
class Book(Base):
__tablename__ = 'books'
title = Column(String(20), primary_key=True)
author_firstName = Column(String(20), ForeignKey('authors.firstName'))
author_lastName = Column(String(20), ForeignKey('authors.lastName'))
36
1 answers
Problem polega na tym, że zdefiniowałeś każdą z kolumn zależnych jako klucze obce oddzielnie, jeśli nie jest to naprawdę to, co zamierzasz, oczywiście chcesz złożony klucz obcy. Sqlalchemy odpowiada na to mówiąc (w niezbyt jasny sposób), że nie może odgadnąć, którego klucza obcego użyć (firstName
lub lastName
).
class Book(Base):
__tablename__ = 'books'
title = Column(String(20), primary_key=True)
author_firstName = Column(String(20))
author_lastName = Column(String(20))
__table_args__ = (ForeignKeyConstraint([author_firstName, author_lastName],
[Author.firstName, Author.lastName]),
{})
Najważniejsze jest to, że ForeignKey
definicje znikają z poszczególnych kolumn, a ForeignKeyConstraint
jest dodawana do zmiennej klasy __table_args__
. Dzięki temu relationship
zdefiniowane na Author.books
działa w sam raz.
61
Author: SingleNegationElimination,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-21 20:24:51
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-21 20:24:51