Hi, all. I've been trying to modify the example of a composite association
proxy
(http://www.sqlalchemy.org/docs/orm/extensions/associationproxy.html#composite-association-proxies)
to fit my needs.
In the documentation example, there is a User object, a Keyword object, and
a UserKeyword association object that stores a 'special_key' for each of a
user's keywords. In the provided example, the result is a collection of
dictionaries where the 'special_key' is the key and the 'keyword' is the
value. I'm trying to inverse that mapping.
In my particular use case (which I've simplified so as to make it as clear
as possible...I hope), I have a User object (a student), a Course object
(an academic course), and a UserCourse association object that stores each
user's grade for each course. My goal is to be able to set a student's
grade something like this:
user.course['math'] = 100
This is what I've come up with, but it (obviously) isn't working yet.
from sqlalchemy import Column, Integer, Text, ForeignKey
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.collections import attribute_mapped_collection
from sqlalchemy.orm import scoped_session, sessionmaker, relationship,
backref
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
# Columns
id = Column(Integer, primary_key=True)
name = Column(Text)
# Relations
courses = association_proxy(
'user_courses',
'course',
creator=lambda k, v: UserCourse(course=k, grade=v)
)
def __init__(self, name):
self.name = name
class Course(Base):
__tablename__ = 'courses'
# Columns
id = Column(Integer, primary_key=True)
title = Column(Text, unique=True)
def __init__(self, title):
self.title = title
# Composite association proxies linking users and preferences
class UserCourse(Base):
__tablename__ = 'user_courses'
# Columns
user_id = Column(Integer, ForeignKey(User.id), primary_key=True)
course_id = Column(Integer, ForeignKey(Course.id), primary_key=True)
grade = Column(Integer)
# Relations
user = relationship(
User,
backref=backref(
'user_courses',
collection_class=attribute_mapped_collection('grade'),
cascade='all, delete-orphan'
)
)
c = relationship('Course')
course = association_proxy('c', 'title')
I'd really appreciate anyone's help here, even if it's just showing me how
to modify the example in the documentation.
--
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 [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/groups/opt_out.