Manuel Faux
Manuel Faux

Reputation: 2457

Update SQLAlchemy relationship

I have two relationships to the same table. When I add an element to one relationship, this does not reflect to the other relationship until I submit the session. Is there a way to force "update" the relationships?

Concrete example:

class Event(ManagerBase):
    """Defines an event."""

    __tablename__ = 'eventing_events'

    id = Column(Integer, primary_key=True)
    device_id = Column(Integer, ForeignKey(EventingDevice.id), nullable=False)
    device = relation(EventingDevice)
    type_id = Column(Integer, ForeignKey(EventType.id), nullable=False)
    type = relation(EventType)
    datetime = Column(DateTime, nullable=False)
    summary = Column(String(500))

    fields = relation("EventFieldValue",
                      viewonly=True,
                      collection_class=attribute_mapped_collection("field.name"))

class EventFieldValue(ManagerBase):
    """The value of a single field of an event."""

    __tablename__ = 'eventing_event_field_values'

    event_id = Column(Integer, ForeignKey(Event.id), primary_key=True)
    event = relation(Event, backref=backref("field_values",
                                            collection_class=attribute_mapped_collection("field")))
    field_id = Column(Integer, ForeignKey(Field.id), primary_key=True)
    field = relation(Field)
    value = Column(Text)

I have two realations from Event to EventFieldValue: fields and field_values (via backref of event). When I add a EventFieldValue to event.field_values, it does not reflect in event.fields until I commit the session.

Upvotes: 2

Views: 7737

Answers (2)

madjar
madjar

Reputation: 12951

Because you have two relations, sqlalchemy have to make requests for each one, and doesn't share their cache in the session.

You should take a look at Association proxies, that seems to be exactly what you need. They allow you to define only one relation and to put proxies on the top of them to access stuff in the relation more easily.

Upvotes: 3

Spencer Rathbun
Spencer Rathbun

Reputation: 14900

Flushing the session should solve this problem. It updates your session with all the new state but doesn't do a commit. You can also look into Refresh/Expire which will reload your objects.

Upvotes: 0

Related Questions