class A(self.Entity): using_options(shortnames=True) key1 = Field(Integer, primary_key=True, autoincrement=False) key2 = Field(String(40), primary_key=True) bs_ = ManyToMany('B', local_colname=['foo', 'bar'], remote_colname="baz")
class PartyCategory(Entity): using_options(tablename='party_category') name = schema.Column(Unicode(40), index=True, nullable=False) color = schema.Column(camelot.types.Color()) # end category definition parties = ManyToMany('Party', lazy=True, backref='categories', tablename='party_category_party', remote_colname='party_id', local_colname='party_category_id') def get_contact_mechanisms(self, virtual_address_type): """Function to be used to do messaging :param virtual_address_type: a virtual address type, such as 'phone' or 'email' :return: a generator that yields strings of contact mechanisms, egg '*****@*****.**' """ for party in self.parties: for party_contact_mechanism in party.contact_mechanisms: contact_mechanism = party_contact_mechanism.contact_mechanism if contact_mechanism: virtual_address = contact_mechanism.mechanism if virtual_address and virtual_address[ 0] == virtual_address_type: yield virtual_address[1] def __unicode__(self): return self.name or '' class Admin(EntityAdmin): verbose_name = _('Category') verbose_name_plural = _('Categories') list_display = ['name', 'color']
class Activitate(Entity): __tablename__ = 'activitati' tip = Column(String(30)) __mapper_args__ = {'polymorphic_on': tip} nume = Field(Unicode(50), required=True, index=True) coordonator = ManyToOne('ResurseUmane', inverse='activitati_coordonate') membrii = ManyToMany('ResurseUmane') aprobata = Column(Boolean) res_fin = OneToMany('ResurseFinanciare', inverse="activitate") res_logistice = ManyToMany('ResursaLogistica') #todo adaugat faze activitate faze = OneToMany("FazeActivitate") def __unicode__(self): return self.nume or '' class Admin(EntityAdmin): verbose_name = 'Activitate' verbose_name_plural = 'Activitati' list_display = ['nume', 'aprobata'] form_display = TabForm([('Importante', Form(['nume', 'coordonator'])), ('Participanti', Form(['membrii'])), ('Resurse', Form(['res_fin', 'res_logistice'])), ('Faze', Form(['faze']))]) field_attributes = dict(ResurseUmane.Admin.field_attributes) form_actions = [RapoarteActivitati()] class Admin2(EntityAdmin): verbose_name = 'Calendar activitati' list_display = ['nume', 'coordonator', 'aprobata'] def get_query(self): session = Session return session.query(Activitate).join(ResurseUmane).filter( ResurseUmane.id == 1) # todo schimbat cu userul # curent class Admin3(EntityAdmin): verbose_name = 'Proiect Departament' verbose_name_plural = 'Proiecte Departament' list_display = ['nume', 'coordonator', 'aprobata', 'tip'] Admin3 = not_editable_admin(Admin3)
class AuthenticationGroup( Entity ): """A group of users (defined by their :class:`AuthenticationMechanism`). Different roles can be assigned to a group. """ __tablename__ = 'authentication_group' name = Column( types.Unicode(256), nullable=False ) members = ManyToMany( AuthenticationMechanism, tablename = 'authentication_group_member', backref = 'groups' ) def __getattr__( self, name ): for role_id, role_name in roles: if role_name == name: for role in self.roles: if role.role_id == role_id: return True return False raise AttributeError( name ) def __setattr__( self, name, value ): for role_id, role_name in roles: if role_name == name: current_value = getattr( self, name ) if value==True and current_value==False: group_role = AuthenticationGroupRole( role_id = role_id ) self.roles.append( group_role ) elif value==False and current_value==True: for group_role in self.roles: if group_role.role_id == role_id: self.roles.remove( group_role ) break break return super( AuthenticationGroup, self ).__setattr__( name, value ) def __unicode__( self ): return self.name or '' class Admin( EntityAdmin ): verbose_name = _('Authentication group') verbose_name_plural = _('Authenication groups') list_display = [ 'name' ] def get_form_display( self ): return forms.TabForm( [(_('Group'), ['name', 'members']), (_('Roles'), [role[1] for role in roles]) ]) def get_field_attributes( self, field_name ): fa = EntityAdmin.get_field_attributes( self, field_name ) if field_name in [role[1] for role in roles]: fa['delegate'] = delegates.BoolDelegate fa['editable'] = True return fa
class A(self.Entity): using_options(shortnames=True) key1 = Field(Integer, primary_key=True, autoincrement=False) key2 = Field(String(40), primary_key=True) bs_ = ManyToMany('B', table=a_b, primaryjoin=lambda: and_(A.key1 == a_b.c.a_key1, A.key2 == a_b.c.a_key2), secondaryjoin=lambda: B.id == a_b.c.b_id, foreign_keys=[a_b.c.a_key1, a_b.c.a_key2, a_b.c.b_id])
class Record(self.Entity): title = Field(String(100)) year = Field(Integer) artist = ManyToOne('Artist') genres = ManyToMany('Genre') # order titles descending by year, then by title using_options(order_by=['-year', 'title']) def __str__(self): return "%s - %s (%d)" % (self.artist.name, self.title, self.year)
class Tag(Entity): __tablename__ = 'tags' name = Column(sqlalchemy.types.Unicode(60), nullable=False) movies = ManyToMany('Movie', tablename='tags_movies__movies_tags', local_colname='movies_id', remote_colname='tags_id') def __unicode__(self): return self.name class Admin(EntityAdmin): form_size = (400, 200) list_display = ['name']
class ResurseUmane(Entity): __tablename__ = 'resurse_umane' username = Column(String(30)) nume = Column(String(50)) doctorat = Column(Boolean) functie = Column(String(30)) activitati = ManyToMany('Activitate') activitati_coordonate = OneToMany('Activitate') taskuri = OneToMany("Task", inverse="membrii") __mapper_args__ = { 'polymorphic_on': functie, } def __unicode__(self): return self.nume or 'Unknown' class Admin(EntityAdmin): verbose_name = 'Resurse Umane' verbose_name_plural = 'Resurse Umane' list_display = ['username', 'nume', 'doctorat', 'functie']
class ResursaLogistica(Entity): __tablename__ = 'resurse_logistice' id = Column(Integer, primary_key=True) type = Column(String(50)) activitati = ManyToMany('Activitate') __mapper_args__ = { 'polymorphic_identity': 'resursa', 'polymorphic_on': type } class Admin(EntityAdmin): verbose_name = 'Resursa' verbose_name_plural = 'Resurse' list_display = ['type'] form_actions = [RaportResurse()] class Admin2(EntityAdmin): verbose_name = 'Resursa Logistica' verbose_name_plural = 'Resurse Logistice' list_display = ['id', 'type'] Admin2 = not_editable_admin(Admin2)
class Genre(self.Entity): name = Field(String(30)) records = ManyToMany('Record', order_by='-title')
class B(self.Entity): using_options(shortnames=True) name = Field(String(60)) as_ = ManyToMany('A', remote_colname=['foo', 'bar'], local_colname="baz")
class A( self.Entity ): using_options( shortnames = True ) name = Field(String(60)) as_ = ManyToMany('A') bs_ = ManyToMany('B')
class Person(self.Entity): using_options(shortnames=True) name = Field(String(30)) friends = ManyToMany('Person') is_friend_of = ManyToMany('Person')
class A(self.Entity): name = Field(String(100)) rel1 = ManyToMany('B') rel2 = ManyToMany('B')
class Party(Entity): """Base class for persons and organizations. Use this base class to refer to either persons or organisations in building authentication systems, contact management or CRM""" using_options(tablename='party') addresses = OneToMany('PartyAddress', lazy=True, cascade="all, delete, delete-orphan") contact_mechanisms = OneToMany('PartyContactMechanism', lazy='select', cascade='all, delete, delete-orphan') shares = OneToMany('SharedShareholder', inverse='established_to', cascade='all, delete, delete-orphan') directed_organizations = OneToMany('DirectedDirector', inverse='established_to', cascade='all, delete, delete-orphan') status = Status() categories = ManyToMany('PartyCategory', tablename='party_category_party', remote_colname='party_category_id', local_colname='party_id') row_type = schema.Column(Unicode(40), nullable=False) __mapper_args__ = {'polymorphic_on': row_type} @property def name(self): return '' def _get_contact_mechanism(self, described_by): """Get a specific type of contact mechanism """ for party_contact_mechanism in self.contact_mechanisms: contact_mechanism = party_contact_mechanism.contact_mechanism if contact_mechanism != None: mechanism = contact_mechanism.mechanism if mechanism != None: if mechanism[0] == described_by: return mechanism def _set_contact_mechanism(self, described_by, value): """Set a specific type of contact mechanism """ assert value[0] in camelot.types.VirtualAddress.virtual_address_types for party_contact_mechanism in self.contact_mechanisms: contact_mechanism = party_contact_mechanism.contact_mechanism if contact_mechanism != None: mechanism = contact_mechanism.mechanism if mechanism != None: if mechanism[0] == described_by: if value and value[1]: contact_mechanism.mechanism = value else: session = orm.object_session( party_contact_mechanism) self.contact_mechanisms.remove( party_contact_mechanism) if party_contact_mechanism.id: session.delete(party_contact_mechanism) return if value and value[1]: contact_mechanism = ContactMechanism(mechanism=value) party_contact_mechanism = PartyContactMechanism( contact_mechanism=contact_mechanism) self.contact_mechanisms.append(party_contact_mechanism) @hybrid.hybrid_property def email(self): return self._get_contact_mechanism(u'email') @email.setter def email_setter(self, value): return self._set_contact_mechanism(u'email', value) @email.expression def email_expression(self): return Email.mechanism @hybrid.hybrid_property def phone(self): return self._get_contact_mechanism(u'phone') @phone.setter def phone_setter(self, value): return self._set_contact_mechanism(u'phone', value) @phone.expression def phone_expression(self): return Phone.mechanism @hybrid.hybrid_property def fax(self): return self._get_contact_mechanism(u'fax') @fax.setter def fax_setter(self, value): return self._set_contact_mechanism(u'fax', value) @fax.expression def fax_expression(self): return Fax.mechanism def _get_address_field(self, name): for party_address in self.addresses: return getattr(party_address, name) def _set_address_field(self, name, value): if not self.addresses: address = PartyAddress() self.addresses.append(address) address = self.addresses[0] setattr(address, name, value) if address.street1 == None and address.street2 == None and address.city == None: session = orm.object_session(address) if address in session.new: session.expunge(address) self.addresses.remove(address) else: session.delete(address) @hybrid.hybrid_property def street1(self): return self._get_address_field(u'street1') @street1.setter def street1_setter(self, value): return self._set_address_field(u'street1', value) @hybrid.hybrid_property def street2(self): return self._get_address_field(u'street2') @street2.setter def street2_setter(self, value): return self._set_address_field(u'street2', value) @hybrid.hybrid_property def city(self): return self._get_address_field(u'city') @city.setter def city_setter(self, value): return self._set_address_field(u'city', value) def full_name(self): aliased_organisation = sql.alias(Organization.table) aliased_person = sql.alias(Person.table) return sql.functions.coalesce( sql.select( [ sql.functions.coalesce(aliased_person.c.first_name, '') + ' ' + sql.functions.coalesce(aliased_person.c.last_name, '') ], whereclause=and_(aliased_person.c.party_id == self.id), ).limit(1).as_scalar(), sql.select( [aliased_organisation.c.name], whereclause=and_(aliased_organisation.c.party_id == self.id), ).limit(1).as_scalar()) full_name = ColumnProperty(full_name, deferred=True)
class A(self.Entity): bs_ = ManyToMany('B')
class Movie(Entity): __tablename__ = 'movies' title = Column(sqlalchemy.types.Unicode(60), nullable=False) short_description = Column(sqlalchemy.types.Unicode(512)) releasedate = Column(sqlalchemy.types.Date) genre = Column(sqlalchemy.types.Unicode(15)) rating = Column(camelot.types.Rating()) # # All relation types are covered with their own editor # director = ManyToOne('Person') cast = OneToMany('Cast') visitor_reports = OneToMany('VisitorReport', cascade='delete') tags = ManyToMany('Tag', tablename='tags_movies__movies_tags', local_colname='tags_id', remote_colname='movies_id') # end short movie definition # # Camelot includes custom sqlalchemy types, like Image, which stores an # image on disk and keeps the reference to it in the database. # # begin image definition cover = Column(camelot.types.Image(upload_to='covers')) # end image definition # # Or File, which stores a file in the upload_to directory and stores a # reference to it in the database # script = Column(camelot.types.File(upload_to='script')) description = Column(camelot.types.RichText) # # Normal python properties can be used as well, but then the # delegate needs be specified in the Admin.field_attributes # @property def visitors_chart(self): # # Container classes are used to transport chunks of data between # the model the gui, in this case a chart # from camelot.container.chartcontainer import BarContainer return BarContainer(range(len(self.visitor_reports)), [vr.visitors for vr in self.visitor_reports]) # begin column_property @ColumnProperty def total_visitors(self): return sql.select([sql.func.sum(VisitorReport.visitors)], VisitorReport.movie_id == self.id) # end column_property # # Each Entity subclass can have a subclass of EntityAdmin as # its inner class. The EntityAdmin class defines how the Entity # class will be displayed in the GUI. Its behavior can be steered # by specifying some class attributes # # To fully customize the way the entity is visualized, the EntityAdmin # subclass should overrule some of the EntityAdmin's methods # class Admin(EntityAdmin): # the list_display attribute specifies which entity attributes should # be visible in the table view list_display = [ 'cover', 'title', 'releasedate', 'rating', ] lines_per_row = 5 # define filters to be available in the table view list_filter = ['genre', ComboBoxFilter('director.full_name')] # if the search function needs to look in related object attributes, # those should be specified within list_search list_search = ['director.full_name'] # begin list_actions # # the action buttons that should be available in the list view # list_actions = [ChangeRatingAction()] # end list_actions drop_action = DropAction() # the form_display attribute specifies which entity attributes should be # visible in the form view form_display = TabForm([ ('Movie', Form([ HBoxForm( [WidgetOnlyForm('cover'), ['title', 'rating', Stretch()]]), 'short_description', 'releasedate', 'director', 'script', 'genre', 'description', ], columns=2)), ('Cast', WidgetOnlyForm('cast')), ('Visitors', WidgetOnlyForm('visitors_chart')), ('Tags', WidgetOnlyForm('tags')) ]) # begin form_actions # # create a list of actions available for the user on the form view # form_actions = [BurnToDisk()] # end form_actions # # additional attributes for a field can be specified in the # field_attributes dictionary # field_attributes = dict( cast=dict(create_inline=True), genre=dict(choices=genre_choices, editable=lambda o: bool(o.title and len(o.title))), releasedate=dict(background_color=lambda o: ColorScheme.orange_1 if o.releasedate and o.releasedate < datetime. date(1920, 1, 1) else None), visitors_chart=dict(delegate=delegates.ChartDelegate), rating=dict(tooltip='''<table> <tr><td>1 star</td><td>Not that good</td></tr> <tr><td>2 stars</td><td>Almost good</td></tr> <tr><td>3 stars</td><td>Good</td></tr> <tr><td>4 stars</td><td>Very good</td></tr> <tr><td>5 stars</td><td>Awesome !</td></tr> </table>'''), smiley=dict(delegate=delegates.SmileyDelegate), script=dict(remove_original=True)) def __unicode__(self): return self.title or ''
class A(self.Entity): using_options(shortnames=True) key1 = Field(Integer, primary_key=True, autoincrement=False) key2 = Field(String(40), primary_key=True) bs_ = ManyToMany('B', table=a_b)
class B(self.Entity): using_options(shortnames=True) name = Field(String(60)) as_ = ManyToMany('A', table=a_b)
class A(self.Entity): as_ = ManyToMany('A') bs_ = ManyToMany('B')
class A(self.Entity): bs_ = ManyToMany('B', table_kwargs={'info': {'test': True}})
class A(self.Entity): key1 = Field(Integer, primary_key=True, autoincrement=False) key2 = Field(String(40), primary_key=True) bs_ = ManyToMany('B')
class B(self.Entity): as_ = ManyToMany('A')
class B(self.Entity): name = Field(String(60)) as_ = ManyToMany('A')