I'm in the processes of open-sourcing a mini-project and need to support 
sqlite -- so I'd like to be a bit easier on DB operations.

The following use-case is puzzling me:

   I want to view a record on TableA, which will show the last 5 related 
objects in TableB and a 'see all' link.

It's represented in a one-to-many relationship:

    import sqlalchemy as sa

    class TableA(Base):
        id = sa.Column(sa.Integer, primary_key=True)
        rel_b = sa.orm.relationship('TableB', primaryjoin='TableA.id== 
TableB.id_a', order_by='TableB.id.desc()')

    class TableB(Base):
        id = sa.Column(sa.Integer, primary_key=True)
        id_a = sa.Column(sa.Integer, sa.ForeignKey("table_a.id"), 
nullable=True)

I looked into `lazy='dynamic'` but ran into a few caveats:
* it is only an 'appendquery' until you iterate the relationship. 
 otherwise you need to call `.limit(n).all()`
* it doesn't cache the value.  so if you iterate `.limit(5)` twice in a 
row, it hits the db twice in a row.  
* it doesn't support eagerloading

I was thinking about extending TableA with a dynamic version of the 
property that I can just 'touch' during my load phase, and then eagerload 
all the `rel_b` associations.

     @property
     def rel_b__latest(self):
           if self._rel_b__latest is None:
                  self._rel_b__latest = 
self.rel_b_dynamic.options(joinedload()..).limit(5).all()
           return self._rel_b__latest

Has anyone else tried to handle something like this before?

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