models.py
author Dmitriy Morozov <morozov@cs.duke.edu>
Sat, 17 May 2008 04:25:28 -0400
changeset 2 b8013798cbfc
parent 1 b139e134d94a
child 4 2a543aeac83d
permissions -rw-r--r--
Added color highlighting + commands (update, view, remove)

from elixir import *
import os.path

class Author(Entity):
    name =      Field(UnicodeText)
    nicknames = OneToMany('AuthorNickname', inverse = 'author')
    papers =    ManyToMany('Paper')

    def __repr__(self): return self.name

class AuthorNickname(Entity):
    name =      Field(UnicodeText)
    author =    ManyToOne('Author')

    def __repr__(self): return self.name

class Paper(Entity):
    authors =   ManyToMany('Author')
    title =     Field(UnicodeText)
    abstract =  Field(UnicodeText)
    tags =      ManyToMany('Tag')

    path =      Field(Text)
    md5 =       Field(Text(64))

    def __repr__(self): return self.title

class Tag(Entity):
    name =      Field(UnicodeText)
    papers =    ManyToMany('Paper')

    def __repr__(self): return self.name

def initDatabase(path, create_tables = True):
    db_path = os.path.abspath(path)
    metadata.bind = 'sqlite:///' + db_path
    setup_all()
    if create_tables:
        create_all()

def get_by_or_init(cls, if_new_set={}, **params):
	"""Call get_by; if no object is returned, initialize an
	object with the same parameters.  If a new object was
	created, set any initial values."""
	
	result = cls.get_by(**params)
	if not result:
		result = cls(**params)
		result.set(**if_new_set)
	return result

Entity.get_by_or_init = classmethod(get_by_or_init)