Hello everybody,

Is it possible to map dictionaries whose keys are objects and the values 
simple integers?

I have the following case :

*In the program, there is one instance of "Options" which contains a 
dictionary. This dictionary has players as keys and integers as values. 
These integers represents the options of the player used as a key.* 

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer

Base = declarative_base()

class Options(Base):

    __tablename__ = "options"
    id = Column(Integer, primary_key=True)

    def __init__(self):
        self.options = {} # Player -> Integer

    def set_options(self, player, value):
        self.options[player] = value

class Player(Base):

    __tablename__ = "players"
    id = Column(Integer, primary_key=True)


opt = Options()

john = Player()
jack = Player()

opt.set_options(john, 2)
opt.set_options(jack, 5)

print(opt.options)


Display :

>>> 
{<__main__.Player object at 0x0000000005611908>: 5, <__main__.Player object 
at 0x0000000005611860>: 2}
>>> 

Of course, in this particular case, it doesn't make a lot of sense and it 
could be designed in another way. It is just an example. I have a lot of 
dictionaries with objects as keys in my project and I have no idea how I 
should map these... and curiously, I am not able to find any example on 
Internet.

I found in the SQLAlchemy documentation explanations related to 
mapped_collection and it sounds to be a bit what I'm looking for.

sqlalchemy.orm.collections.mapped_collection(keyfunc)
> *"A dictionary-based collection type with arbitrary keying."*


http://docs.sqlalchemy.org/en/latest/orm/collections.html

The Composite Association example seems also to be a good base to do what I 
want :

http://docs.sqlalchemy.org/en/latest/orm/extensions/associationproxy.html#composite-association-proxy

Do you have suggestions ? Is it even possible ? What would be the good 
method to map that ?

Thank you :-)

-- 
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.

Reply via email to