Skip to content

Instantly share code, notes, and snippets.

@storborg
Created June 13, 2009 22:33
Show Gist options
  • Save storborg/129457 to your computer and use it in GitHub Desktop.
Save storborg/129457 to your computer and use it in GitHub Desktop.
"""
sqlalchemy composite column example.
"""
from sqlalchemy import *
from sqlalchemy.orm import *
metadata = MetaData('sqlite://')
vertices = Table('vertices', metadata,
Column('id', Integer, primary_key=True),
Column('x1', Integer),
Column('y1', Integer),
Column('x2', Integer),
Column('y2', Integer),
)
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __composite_values__(self):
return [self.x, self.y]
def __set_composite_values__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return other.x == self.x and other.y == self.y
def __ne__(self, other):
return not self.__eq__(other)
class Vertex(object):
def __init__(self, start, end):
self.start = start
self.end = end
mapper(Vertex, vertices, properties={
'start': composite(Point, vertices.c.x1, vertices.c.y1),
'end': composite(Point, vertices.c.x2, vertices.c.y2)
})
metadata.drop_all()
metadata.create_all()
session = create_session()
v = Vertex(Point(3, 4), Point(5, 6))
session.add(v)
session.flush()
print session.query(Vertex).filter(Vertex.start == Point(3, 4)).all()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment