On Oct 1, 2013, at 8:30 PM, Adam Tauno Williams <
awil...@whitemice.org> wrote:
>
> Ok, I have something working; but it seems like there should be a more
> elegant way. I am declaring an alias of the Project mapper class in
> order to make it work - that seems awkward.
it looks fine to me? if you want to query self-referentially in SQL, you need an alias. that SQLAlchemy lets you use the alias here just as you would in SQL, lets you add it to the mapping and all with no extra hacks, seems natural to me...guess it has to do with where you're coming form.
> Is there anyway to embed
> the appropriate aliasing in the single statement? I cannot figure out
> how to reference a instance of the __table__.alias() in the same
> statement.
you can refer to __table__.alias() in much the same way, just use the .c. attribute to get at the columns, not sure what aspect you're getting at here, is it that you want the column property declared inside the class declaration? you can use __declare_last__ as one option, here is that:
class Project(Base):
__tablename__ = 'project'
object_id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('project.object_id'))
@classmethod
def __declare_last__(cls):
p_alias = cls.__table__.alias()
cls.project_count = column_property(
select([func.count(p_alias.c.object_id)]).\
where(p_alias.c.parent_id == cls.object_id).
as_scalar()
)
>
> from sqlalchemy.orm import aliased
>
> project_count_alias = aliased(Project)
>
> Project.project_count = column_property(
> select([func.count(project_count_alias.object_id), ]).\
> where(project_count_alias.parent_id==Project.object_id).
> as_scalar(), )
>
> --
> Adam Tauno Williams <mailto:
awil...@whitemice.org> GPG D95ED383
> Systems Administrator, Python Developer, LPI / NCLA
>
> --
> 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+...@googlegroups.com.
> To post to this group, send email to
sqlal...@googlegroups.com.
> Visit this group at
http://groups.google.com/group/sqlalchemy.
> For more options, visit
https://groups.google.com/groups/opt_out.