SQLAlchemy - problem with MappedCollection

I have some problems setting up a dictionary collection in SQLAlchemy Python:

I use a declarative definition of tables. I have a table Itemin a 1: N ratio with a table Record. I established the relationship using the following code:

_Base = declarative_base()

class Record(_Base):
    __tablename__ = 'records'

    item_id = Column(String(M_ITEM_ID), ForeignKey('items.id'))
    id = Column(String(M_RECORD_ID), primary_key=True)
    uri = Column(String(M_RECORD_URI))
    name = Column(String(M_RECORD_NAME))

class Item(_Base):
    __tablename__ = 'items'

    id = Column(String(M_ITEM_ID), primary_key=True)

    records = relation(Record, collection_class=column_mapped_collection(Record.name), backref='item')

Now I want to work with Itemand Records. Let me create some objects:

i1 = Item(id='id1')
r = Record(id='mujrecord')

And now I want to link these objects with the following code:

i1.records['source_wav'] = r

but Record rdoes not set the attribute name(foreign key). Is there a solution how to automatically provide this? (I know that setting a foreign key during creation Recordworks, but for me this is not very good).

Many thanks

+3
3

- :

from sqlalchemy.orm import validates

class Item(_Base):
    [...]

    @validates('records')
    def validate_record(self, key, record):
      assert record.name is not None, "Record fails validation, must have a name"
      return record

:

>>> i1 = Item(id='id1')
>>> r = Record(id='mujrecord')
>>> i1.records['source_wav'] = r
Traceback (most recent call last):
  [...]
AssertionError: Record fails validation, must have a name
>>> r.name = 'foo'
>>> i1.records['source_wav'] = r
>>> 
+2

, :

from sqlalchemy.orm import validates

class Item(_Base):
    [...]

    @validates('records')
    def validate_record(self, key, record):
      record.name=key
      return record

, , Gunnlaugur, , - , .

+1

You have:

backref='item'

This is a typo for

backref='name'

?

0
source

Source: https://habr.com/ru/post/1707193/


All Articles