On 11/14/2016 07:12 AM, Michael Williamson wrote:
Is there a way to use relationship() with hybrid properties? When using
foreign() to mark the foreign key and trying to set the relationship, it
seems to treat the underlying column as the foreign key rather than the
hybrid property. For instance (apologies for triteness):
from __future__ import unicode_literals
from sqlalchemy import create_engine, func, Column, Integer, String
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import foreign, relationship, remote, Session
Base = declarative_base()
class Person(Base):
__tablename__ = "person"
id = Column(Integer, primary_key=True)
name = Column(String)
class Book(Base):
__tablename__ = "book"
id = Column(Integer, primary_key=True)
person_id = Column(String)
@hybrid_property
def author_id(self):
return int(self.person_id[1:])
@author_id.expression
def author_id(self):
return func.substr(self.person_id, 2)
@author_id.setter
def author_id(self, value):
self.person_id = "A{}".format(value)
author = relationship(
Person,
primaryjoin=lambda:
remote(Person.id) == foreign(Book.author_id),
)
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(engine)
session = Session(engine)
bob = Person(id=42, name="Bob")
session.add(bob)
session.flush()
session.add(Book(author=bob))
session.commit()
print(session.query(Book).one().person_id)
assert session.query(Book).one().person_id == "A42"
In this case, person_id will be set to "42" rather than "A42". I just
wanted to check that was unsupported, rather than an error on my part
(or if there's an alternative that'll give similar functionality in
the ORM i.e. being able to set the relationship without the foreign ID
necessarily having been set).
on the *setter* side, no, that won't work, relationship() doesn't call
upon hybrid setters when it actually does its persistence work.
Thanks
Michael
--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper
http://www.sqlalchemy.org/
To post example code, please provide an MCVE: Minimal, Complete, and Verifiable
Example. See http://stackoverflow.com/help/mcve for a full description.
---
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.