Re: [Sqlalchemy-tickets] [sqlalchemy] #2808: AssociationProxy should use keywords on create
Brought to you by:
zzzeek
|
From: sqlalchemy <mi...@zz...> - 2013-08-26 15:17:03
|
#2808: AssociationProxy should use keywords on create
-----------------------------------+----------------------------------
Reporter: schlamar | Owner: zzzeek
Type: enhancement | Status: reopened
Priority: medium | Milestone: 0.8.xx
Component: ext | Severity: minor - half an hour
Resolution: | Keywords:
Progress State: completed/closed |
-----------------------------------+----------------------------------
Comment (by zzzeek):
Replying to [comment:11 schlamar]:
> Plus, your example (with creator) doesn't work because !UserKeyword is
not yet defined for the User class. So you would have to refactor the
complete example to make it work (which could be really messy if you have
to use this solution in production code).
The my_association_proxy() function doesn't need access to the UserKeyword
class. Feel free to actually run the recipe in context of your original
example:
{{{
#!python
from sqlalchemy import Column, Integer, ForeignKey, String
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
def my_association_proxy(src, target):
def create(value):
target_cls = prox.target_class
return target_cls(**{target: value})
prox = association_proxy(src, target, creator=create)
return prox
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String(64))
keywords = my_association_proxy('user_keywords', 'keyword')
class UserKeyword(Base):
__tablename__ = 'user_keyword'
user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)
keyword_id = Column(Integer, ForeignKey('keyword.id'),
primary_key=True)
# bidirectional attribute/collection of "user"/"user_keywords"
user = relationship(User, backref=backref("user_keywords",
cascade="all, delete-orphan"))
# reference to the "Keyword" object
keyword = relationship("Keyword")
class Keyword(Base):
__tablename__ = 'keyword'
id = Column(Integer, primary_key=True)
keyword = Column(String(64))
user = User(name='log')
for kw in (Keyword(keyword='new_from_blammo'),
Keyword(keyword='its_big')):
user.keywords.append(kw)
print(user.keywords)
}}}
--
Ticket URL: <http://www.sqlalchemy.org/trac/ticket/2808#comment:13>
sqlalchemy <http://www.sqlalchemy.org/>
The Database Toolkit for Python
|