On 10/7/15 5:21 PM, Marten Jakobsen wrote:
> Hi,
>
> I'm using the UniqueObject recipe [1] for simple two column tables
> and it works just fine, but what is the best way to use it with tables
> containing relationships?
>
> I usually did:
>
>
> mytime = Timestamp.as_unique(session, timestamp=value)
> session.flush()
> fingerprint = Fingerprint.as_unique(session, fingerprint='foo',
> ts_id=mytime.id)
>
> Fingerprint class looks like this (timestamp is optional):
>
> class Fingerprint(UniqueMixin, Base):
>     __tablename__ = 'fingerprint'
>     id = Column(mysql.MEDIUMINT(unsigned=True), primary_key=True)
>     fingerprint = Column(mysql.CHAR(16), nullable=False)
>     ts_id       = Column(mysql.SMALLINT(unsigned=True),
> ForeignKey('timestamp.id'))
>
>     timestamp          = relationship('Timestamp')

>
>     @classmethod
>     def unique_hash(cls, **kw):
>         return str(kw)
>
>     @classmethod
>     def unique_filter(cls, query, fingerprint, ts_id=None):
>         return query.filter(Fingerprint.fingerprint == fingerprint,
> Fingerprint.ts_id == ts_id)
>
>
> to get rid of session.flush() I changed it to (which gave me a >100%
> speedup):
>
>
> mytime = Timestamp.as_unique(session, timestamp=value)
> fingerprint = Fingerprint.as_unique(session, fingerprint='foo',
> timestamp=mytime)
>
> (also adjusting the unique_filter() to: ...,
> Fingerprint.timestamp==timestamp)
>
> but it also shows this warning:
>
> /usr/lib64/python2.7/site-packages/sqlalchemy/orm/relationships.py:1392:
> SAWarning: Got None for value of column timestamp.id; this is
> unsupported for a relationship comparison and will not currently
> produce an IS comparison (but may in a future release)
>   "(but may in a future release)" % column)
Hmmmm.....  I guess that *does* sort of work in that way, because the
fact that mytime has no ID means that we know Fingerprint has to be
created as well.    I was going to suggest bundling the creation of
Fingerprint into Timestamp.  But actually, I'd just modify the recipe
here to see that when the incoming "mytime" object has no primary key
you skip the Query altogether that would normally be looking for
Fingerprint,  this would be inside of the _unique function.
 

>
>
> Is it ok to use the latter way? (will it result in the same table
> content?)
>
> thanks,
> Marten
>
>
>
> [1]
> https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/UniqueObject
>


-- 
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 http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to