class User(BaseModel, UserMixin): username = CharField(unique=True, index=True) password = CharField() email = CharField() first_name = CharField() last_name = CharField() # confirmed_at = DateTimeField(null=True) active = BooleanField(default=True) workplace = ForeignKeyField(Company, backref='works_for') roles = ManyToManyField(Role, backref='users', through_model=UserRoleDeferred) approves_for = ManyToManyField(Company, backref='approved_by', through_model=ApproverCompanyDeferred) full_name = property(lambda self: "%s %s" % (self.first_name, self.last_name)) def gravatar_url(self, size=80): return "http://www.gravatar.com/avatar/%s?d=identicon&s=%d" % \ (md5(self.email.strip().lower().encode('utf-8')).hexdigest(), size) class Meta: order_by = ('username', ) table_alias = 'u' def __str__(self): return self.full_name
class Target(TargetdbBase): catalogid = ForeignKeyField(column_name='catalogid', model=catalogdb.Catalog, field='catalogid') dec = DoubleField(null=True) epoch = FloatField(null=True) pk = AutoField() pmdec = FloatField(null=True) pmra = FloatField(null=True) ra = DoubleField(null=True) designs = ManyToManyField(Design, through_model=AssignmentDeferred, backref='targets') positioners = ManyToManyField(Positioner, through_model=AssignmentDeferred, backref='targets') instruments = ManyToManyField(Instrument, through_model=AssignmentDeferred, backref='targets') cadences = ManyToManyField(Cadence, through_model=CartonToTargetDeferred, backref='targets') parallax = FloatField(null=True) class Meta: table_name = 'target'
class Account(Model): email = CharField() breaches = ManyToManyField(Breach, backref="accounts") pates = ManyToManyField(Paste, backref="accounts") class Meta: database = DB db_table = "accounts"
class Plate(OperationsDBModel): chunk = TextField(null=True) comment = TextField(null=True) current_survey_mode = ForeignKeyField(column_name='current_survey_mode_pk', null=True, model=SurveyMode, field='pk') design = ForeignKeyField(column_name='design_pk', null=True, model=Design, backref='plates', field='pk') epoch = FloatField(null=True) location_id = BigIntegerField(column_name='location_id', null=True) name = TextField(null=True) pk = PrimaryKeyField() plate_completion_status_pk = ForeignKeyField( column_name='plate_completion_status_pk', null=True, model=PlateCompletionStatus, backref='plates', field='pk') plate_id = IntegerField(column_name='plate_id', unique=True) plate_location = ForeignKeyField(column_name='plate_location_pk', model=PlateLocation, field='pk') plate_run = ForeignKeyField(column_name='plate_run_pk', null=True, model=PlateRun, field='pk') rerun = TextField(null=True) temperature = FloatField(null=True) tile_id = IntegerField(column_name='tile_id', null=True) tile = ForeignKeyField(column_name='tile_pk', null=True, model=Tile, backref='plates', field='pk') surveys = ManyToManyField(model=Survey, through_model=PlateSurveyThroughModel, backref='plates') statuses = ManyToManyField(model=PlateStatus, through_model=PlateStatusThroughModel, backref='plates') @property def mangadb_plate(self): """One-to-one backref for mangadb.plate.platedb_plate.""" from sdssdb.peewee.operationsdb import mangadb return mangadb.Plate.get_or_none(platedb_plate_pk=self.pk) class Meta: db_table = 'plate' schema = 'platedb' print_fields = ['plate_id']
class Track(BaseModel, EmojiModelMixin): EMOJI = ':musical_note:' id = CharField(primary_key=True) name = CharField() track_number = IntegerField(null=True) duration_ms = IntegerField(null=True) explicit = BooleanField(null=True) popularity = IntegerField(null=True) href = CharField(null=True) spotify_url = CharField(null=True) preview_url = CharField(null=True) uri = CharField() album = ForeignKeyField(Album, backref='tracks') artists = ManyToManyField(Artist, backref='tracks') def __str__(self): return self.name def get_first_artist(self): if self.artists: return self.artists.first() return None @classmethod def get_emoji(cls): return emojize(cls.EMOJI, use_aliases=True)
class Book(BaseModel): book_id = IntegerField(index=True) title = CharField() subtitle = CharField(null=True) language = CharField(null=True) year = IntegerField(null=True) series = CharField(null=True) authors = ManyToManyField( Author, backref="books", through_model=BookAuthorsDeferred) augmented = BooleanField(null=True, default=False) annotation = TextField(null=True) cover_image = DeferredForeignKey("File", field="file_id", null=True) ebook_fb2 = DeferredForeignKey("File", field="file_id", null=True) ebook_mobi = DeferredForeignKey("File", field="file_id", null=True) def __repr__(self): return "Book({!r}, {!r}, {!r}, {!r}, {!r}, {!r}, ...)".format( self.book_id, self.title, self.subtitle, self.language, self.year, self.series) def __str__(self): return repr(self)
class Plugging(OperationsDBModel): cartridge = ForeignKeyField(column_name='cartridge_pk', null=True, model=Cartridge, backref='pluggings', field='pk') fscan = IntegerField(column_name='fscan_id', null=True) fscan_mjd = IntegerField(null=True) name = TextField(null=True) pk = PrimaryKeyField() plate = ForeignKeyField(column_name='plate_pk', model=Plate, backref='pluggings', field='pk') status = ForeignKeyField(column_name='plugging_status_pk', model=PluggingStatus, field='pk', backref='pluggings') instruments = ManyToManyField(model=Instrument, through_model=PluggingInstrumentDeferred, backref='pluggings') class Meta: db_table = 'plugging' schema = 'platedb'
class Exercise(BaseModel): subject = CharField() date = DateTimeField() users = ManyToManyField(User, backref='exercises') is_archived = BooleanField() def __str__(self): return self.subject
class Question(BaseModel): title = CharField() details = CharField(max_length=1024, default='no details') # f key asker = ForeignKeyField(User, backref='questions') options = ManyToManyField(Option, backref='questions')
class Artist(BaseModel): id = CharField(primary_key=True) name = CharField() image = CharField(null=True) popularity = IntegerField(null=True) href = CharField(null=True) spotify_url = CharField(null=True) uri = CharField() genres = ManyToManyField(Genre, backref='artists')
class Album(BaseModel, EmojiModelMixin): EMOJI = ':cd:' ALBUM_TYPES = ( 'album', 'single', 'compilation', ) id = CharField(primary_key=True) name = CharField() label = CharField(null=True) image = CharField(null=True) popularity = IntegerField(null=True) href = CharField(null=True) spotify_url = CharField(null=True) album_type = CharField(null=True) uri = CharField() release_date = DateField() release_date_precision = CharField(null=True) genres = ManyToManyField(Genre, backref='albums') artists = ManyToManyField(Artist, backref='albums') def __str__(self): return self.name def get_first_artist(self): if self.artists: return self.artists.first() return None @staticmethod def parse_release_date(release_date: str, release_date_precision) -> datetime.date: if release_date_precision == 'day': return datetime.datetime.strptime(release_date, '%Y-%m-%d').date() elif release_date_precision == 'month': return datetime.datetime.strptime(release_date, '%Y-%m').date() elif release_date_precision == 'year': return datetime.datetime.strptime(release_date, '%Y').date() @classmethod def get_emoji(cls): return emojize(cls.EMOJI, use_aliases=True)
class Gaia_DR2(CatalogdbModel): source_id = BigIntegerField(primary_key=True) tmass_best = ManyToManyField(TwoMassPSC, through_model=_Gaia_DR2_TwoMass_Deferred, backref='gaia_best') class Meta: table_name = 'gaia_dr2_source'
class Part(BaseModel): block = CharField() model = CharField() library = CharField() symbol = CharField() datasheet = CharField() description = TextField(default='') footprint = CharField() params = ManyToManyField(Param, backref='parts_params') spice = TextField(default='') mods = ManyToManyField(Mod, backref='blocks') props = ManyToManyField(Prop, backref='blocks') stock = ManyToManyField(Stock, backref='parts_stock') pins = ManyToManyField(Pin, backref='blocks') def __str__(self): return ' '.join([str(self.id), self.block, self.model]) @property def spice_params(self): if self.spice.upper().find('SUBCKT') != -1: return {} without_comments = filter(lambda line: line[0] != '*', self.spice) replace_plus_joints = ''.join(without_comments).replace( '+', ' ').replace('(', ' ').replace(')', ' ').upper() reduce_double_spaces = ' '.join(replace_plus_joints.split()).replace( ' =', '=').replace('= ', '=') spice_model = reduce_double_spaces.split(' ') params = {} for param in spice_model: if param.find('=') == -1: continue param, value = param.split('=') try: params[param] = float(value) except: params[param] = value return params
class SDSS_DR14_APOGEE_Star(DeprecatedModel): apstar_id = TextField(primary_key=True) apogee_id = TextField() visits = ManyToManyField(SDSS_DR14_APOGEE_Visit, through_model=_APOGEE_Star_Visit_Deferred, backref='stars') class Meta: table_name = 'sdss_dr14_apogeestar'
class Movies(BaseModel): title = CharField() year = IntegerField(null=True) imdb_id = IntegerField(null=True) tmdb_id = IntegerField(null=True) genres = ManyToManyField(Genres, backref='movies') def to_dict(self): return model_to_dict(self, manytomany=True) def __str__(self): return self.title
def __init__(self, *args, **kwargs): from peewee import ManyToManyField # avoid circular dependencies from .membership import Membership from .user import User users = ManyToManyField(model=User, backref='projects', through_model=Membership) self._meta.add_field('users', users) super().__init__(*args, **kwargs)
def __init__(self, *args, **kwargs): from peewee import ManyToManyField # pylint: disable=cyclic-import from .contribution import Contribution from .user import User # pylint: enable=cyclic-import users = ManyToManyField( model=User, backref='articles', through_model=Contribution) self._meta.add_field('users', users) super().__init__(*args, **kwargs)
class Product(Model): name = CharField(index=True) unit_price = MoneyField() instock = IntegerField() owner = ForeignKeyField(User, backref='products') # one-to-many field description = TextField(index=True) tags = ManyToManyField(Tag) class Meta: database = db constraints = [peewee.Check('instock >= 0')] db_table = 'products'
class Album(BaseModel): ALBUM_TYPES = ( 'album', 'single', 'compilation', ) id = CharField(primary_key=True) name = CharField() label = CharField(null=True) image = CharField(null=True) popularity = IntegerField(null=True) href = CharField(null=True) spotify_url = CharField(null=True) # external_urls['spotify'] album_type = CharField(null=True) uri = CharField() genres = ManyToManyField(Genre, backref='albums') artists = ManyToManyField(Artist, backref='albums') def get_first_artist(self): if self.artists: return self.artists.first() return None
def __init__(self, *args, **kwargs): from peewee import ManyToManyField # pylint: disable=cyclic-import from .article import Article from .contribution import Contribution from .project import Project from .membership import Membership # pylint: enable=cyclic-import # collaborator projects = ManyToManyField(model=Project, backref='users', through_model=Membership) self._meta.add_field('projects', projects) # contributor articles = ManyToManyField(Article, backref='users', through_model=Contribution) self._meta.add_field('articles', articles) super().__init__(*args, **kwargs)
class Component(BaseModel): name = CharField() user_id = CharField() width = DoubleField() height = DoubleField() website = ForeignKeyField(Website, backref="component") tags = ManyToManyField(Tag, backref="components") @property def tag_ids(self): return [str(t.id) for t in self.tags] def to_dict(self): return model_to_dict(self, recurse=False, extra_attrs=["tag_ids"])
class ReadingList(BaseModel): name = CharField() slug = CharField(primary_key=True) data = PickleField(null=True) comics = ManyToManyField(Comic, backref="readinglists", through_model=ComicIndexDeferred) cb_limit_active = BooleanField(null=True) limit_num = IntegerField(null=True) cb_only_read_active = BooleanField(null=True) cb_purge_active = BooleanField(null=True) cb_optimize_size_active = BooleanField(null=True) sw_syn_this_active = BooleanField(null=True) end_last_sync_num = IntegerField(default=0) totalCount = IntegerField()
class Book(BaseModel): id = PrimaryKeyField(null=False) google_book_id = CharField(max_length=12, unique=True) title = CharField(max_length=255) subtitle = CharField(max_length=255, null=True) description = TextField(null=True) published_date = CharField(max_length=45, null=True) isbn_10 = CharField(max_length=10, null=True, unique=True) isbn_13 = CharField(max_length=13, null=True, unique=True) publisher = CharField(max_length=255, null=True) page_count = CharField(max_length=45, null=True) print_type = CharField(max_length=45, null=True) language = CharField(max_length=45, null=True) main_category = CharField(max_length=255, null=True) authors = ManyToManyField(Author, backref='books', through_model=AuthorThroughDeferred)
class SDSS_DR16_APOGEE_Star(CatalogdbModel): apstar_id = TextField(primary_key=True) apogee_id = TextField() gaia = ForeignKeyField(Gaia_DR2, field='source_id', column_name='gaia_source_id', object_id_name='gaia_source_id', backref='apogee_star') visits = ManyToManyField(SDSS_DR16_APOGEE_Visit, through_model=_APOGEE_Star_Visit_Deferred, backref='stars') class Meta: table_name = 'sdss_dr16_apogeestar'
class Track(BaseModel): id = CharField(primary_key=True) name = CharField() track_number = IntegerField(null=True) duration_ms = IntegerField(null=True) explicit = BooleanField(null=True) popularity = IntegerField(null=True) href = CharField(null=True) spotify_url = CharField(null=True) # external_urls['spotify'] preview_url = CharField(null=True) uri = CharField() album = ForeignKeyField(Album, backref='tracks') artists = ManyToManyField(Artist, backref='tracks') def get_first_artist(self): if self.artists: return self.artists.first() return None
class Group(Model): """Represent a Group. Repräsentiert eine Gruppe""" books: T.Union[peewee.ManyToManyQuery, peewee.ManyToManyField]\ = ManyToManyField(Book, 'groups') name: T.Union[str, CharField] = CharField(primary_key=True) def __str__(self): return utils.get_name('Group[{}]').format(self.name) repr_data = { 'ein': 'eine', 'name': 'Gruppe', 'id': 'Name' } str_fields = (name,) pk_name = 'name'
class Artist(BaseModel, EmojiModelMixin): EMOJI = ':busts_in_silhouette:' id = CharField(primary_key=True) name = CharField() image = CharField(null=True) popularity = IntegerField(null=True) href = CharField(null=True) spotify_url = CharField(null=True) uri = CharField() genres = ManyToManyField(Genre, backref='artists') def __str__(self): return self.name @classmethod def get_emoji(cls): return emojize(cls.EMOJI, use_aliases=True)
class Library(Model): """Represent the libraries a Person has access to. Speichert die Bibliotheken, zu denen eine Person Zugang hat.""" people: T.Union[peewee.ManyToManyQuery, peewee.ManyToManyField]\ = ManyToManyField(Person, 'libraries') books: T.Union[peewee.ManyToManyQuery, peewee.ManyToManyField] name: T.Union[str, CharField] = CharField(primary_key=True) pay_required: T.Union[bool, BooleanField] = BooleanField(default=True) def __str__(self): return utils.get_name('Library[{}]').format(self.name) repr_data = { 'ein': 'eine', 'name': 'Bibliothek', 'id': 'Name' } str_fields = (name,) pk_name = 'name'
class Users(BaseModel): email = CharField(unique=True) phone = CharField(unique=True, null=True) groups = ManyToManyField(Groups, backref='users') password = CharField(max_length=512, null=True) name = CharField(unique=True, null=True) auth_mode = CharField(max_length=64, default='login') #login social level = CharField( default='customer') # root | superuser | staff | customer | seller email_verified = BooleanField(default=False) phone_verified = BooleanField(default=False) info = JSONField(default=lambda: {}) is_active = BooleanField(default=True) last_login = DateTimeField(null=True) login_count = IntegerField(default=0) logins_failed = IntegerField(default=0) login_tries = IntegerField(default=0) @property def login(self): return self.logins.get()
class Exercise(BaseModel): subject = CharField() date = DateTimeField() users = ManyToManyField(User, backref='exercises') is_archived = BooleanField(default=False, index=True) due_date = DateTimeField(null=True) notebook_num = IntegerField(default=0) order = IntegerField(default=0, index=True) def open_for_new_solutions(self) -> bool: if self.due_date is None: return not self.is_archived return datetime.now() < self.due_date and not self.is_archived @classmethod def get_objects(cls, fetch_archived: bool = False): exercises = cls.select().order_by(Exercise.order) if not fetch_archived: exercises = exercises.where(cls.is_archived == False) # NOQA: E712 return exercises def as_dict(self) -> Dict[str, Any]: return { 'exercise_id': self.id, 'exercise_name': self.subject, 'is_archived': self.is_archived, 'notebook': self.notebook_num, 'due_date': self.due_date, } @staticmethod def as_dicts(exercises: Iterable['Exercise']) -> ExercisesDictById: return {exercise.id: exercise.as_dict() for exercise in exercises} def __str__(self): return self.subject