Association Proxy SQLAlchemy

后端 未结 2 1691
时光说笑
时光说笑 2020-12-16 03:15

This source details how to use association proxies to create views and objects with values of an ORM object.

However, when I append an value that matches an existin

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 03:55

    The example shown on the documentation page you link to is a composition type of relationship (in OOP terms) and as such represents the owns type of relationship rather then uses in terms of verbs. Therefore each owner would have its own copy of the same (in terms of value) keyword.

    In fact, you can use exactly the suggestion from the documentation you link to in your question to create a custom creator method and hack it to reuse existing object for given key instead of just creating a new one. In this case the sample code of the User class and creator function will look like below:

    def _keyword_find_or_create(kw):
        keyword = Keyword.query.filter_by(keyword=kw).first()
        if not(keyword):
            keyword = Keyword(keyword=kw)
            # if aufoflush=False used in the session, then uncomment below
            #session.add(keyword)
            #session.flush()
        return keyword
    
    class User(Base):
        __tablename__ = 'user'
        id = Column(Integer, primary_key=True)
        name = Column(String(64))
        kw = relationship("Keyword", secondary=lambda: userkeywords_table)
        keywords = association_proxy('kw', 'keyword', 
                creator=_keyword_find_or_create, # @note: this is the 
                )
    

提交回复
热议问题