コード例 #1
0
ファイル: raspnagr.py プロジェクト: SevenLines/university-map
class Auditory(db.Model):
    __tablename__ = "auditories"

    id = db.Column('id_60', db.Integer, primary_key=True)
    title = db.Column("obozn", db.String(20))
    korp_id = db.Column("korp", db.Integer, db.ForeignKey('vackorp.id_67'))
    maxstud = db.Column(db.SmallInteger)
    specoborud = db.Column(db.SmallInteger)

    def __str__(self, *args, **kwargs):
        return "<Auditory: {}>".format(self.title.strip())

    def __repr__(self):
        return str(self)

    @staticmethod
    def get_key(title: str):
        title = title.strip().lower().replace("_вт", "").replace("-", "").replace(".", "")
        title = title.translate(LETTER_MAPPING_TABLE)
        return title

    @staticmethod
    def get_new_aud_title(title):
        return f"enter_{Auditory.get_key(title)}"

    raspnagr = db.relationship('Raspnagr', backref=db.backref('auditory', lazy='joined'), lazy='dynamic')
    raspis = db.relationship('Raspis', backref=db.backref('auditory', lazy='joined'), lazy='dynamic')
コード例 #2
0
ファイル: models.py プロジェクト: JiehuiSun/DataTools
class SQLModel(db.Model):
    """
    sql
    """
    __tablename__ = "sql_model"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128), nullable=False, comment="SQL名")
    project_id = db.Column(db.ForeignKey("requirement_model.id"))
    project = db.relationship('RequirementModel',
                              backref=db.backref('sql_model', lazy='dynamic'))
    database_id = db.Column(db.ForeignKey("database_model.id"))
    database = db.relationship('DatabaseModel',
                               backref=db.backref('sql_model', lazy='dynamic'))
    content = db.Column(db.Text, nullable=False, comment="sql语句")
    special_field = db.Column(db.String(64), nullable=False, comment="特殊字段")
    parent_id = db.Column(db.Integer, db.ForeignKey("sql_model.id"))
    parent = db.relationship("SQLModel", remote_side=[id])
    parent_field = db.Column(db.String(64), nullable=False, comment="父字段")
    is_deleted = db.Column(db.Boolean, default=False)
    dt_create = db.Column(db.DateTime, default=time_utils.now_dt)
    dt_update = db.Column(db.DateTime,
                          default=time_utils.now_dt,
                          onupdate=time_utils.now_dt)

    def __repr__(self):
        return self.name

    def __str__(self):
        return self.name
コード例 #3
0
class Venta(db.Model):
    id = db.Column(db.Integer, unique=True, primary_key=True)
    fecha = db.Column(db.Text)
    cantidad = db.Column(db.Integer)
    silla = db.relationship('Silla',
                            backref=db.backref('ventas', lazy='dynamic'))
    conferencia = db.relationship('Conferencia',
                                  backref=db.backref('ventas', lazy='dynamic'))

    def __init__(self, fecha, cantidad, silla, conferencia):
        self.fecha = fecha
        self.cantidad = cantidad
        self.silla = silla
        self.conferencia = conferencia
コード例 #4
0
ファイル: raspnagr.py プロジェクト: SevenLines/university-map
class WishAuddPara(db.Model):
    __tablename__ = "wishauddpara"

    wish = db.Column("wish", db.Integer, db.ForeignKey('wishaudd.id_62'), primary_key=True)
    para = db.Column("para", db.SmallInteger)

    wish_instance = db.relationship('WishAudd', backref=db.backref('pairs', lazy='joined'))
コード例 #5
0
ファイル: models.py プロジェクト: JiehuiSun/DataTools
class RequirementModel(db.Model):
    """
    需求
    """
    __tablename__ = "requirement_model"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128), nullable=False, comment="项目名")
    comments = db.Column(db.String(128), nullable=True, comment="备注")
    user_mail_list = db.Column(db.Text, nullable=False, comment="用户邮箱")
    # sqls = db.relationship('SQLModel', backref='project', lazy='dynamic')
    # tasks = db.relationship('TasksModel', backref='project', lazy='dynamic')
    task_type_id = db.Column(db.ForeignKey("task_type_model.id"))
    task_type = db.relationship('TaskTypeModel',
                                backref=db.backref('requirement_model',
                                                   lazy='dynamic'))
    is_deleted = db.Column(db.Boolean, default=False)
    dt_create = db.Column(db.DateTime, default=time_utils.now_dt)
    dt_update = db.Column(db.DateTime,
                          default=time_utils.now_dt,
                          onupdate=time_utils.now_dt)

    def __repr__(self):
        return self.name

    def __str__(self):
        return self.name
コード例 #6
0
ファイル: raspnagr.py プロジェクト: SevenLines/university-map
class Discipline(db.Model):
    __tablename__ = "vacpred"
    id = db.Column('id_15', db.Integer, primary_key=True)
    title = db.Column("pred", db.String(250))
    titles = db.Column("preds", db.String(250))

    raspnagr = db.relationship('Raspnagr', backref=db.backref('discipline', lazy='joined'), lazy='dynamic')
コード例 #7
0
ファイル: raspnagr.py プロジェクト: SevenLines/university-map
class Chair(db.Model):
    __tablename__ = "vackaf"
    id = db.Column('id_17', db.Integer, primary_key=True)
    title = db.Column("kaf", db.String(100))
    short_title = db.Column("sokr", db.String(10))

    raspnagr = db.relationship('Raspnagr', backref=db.backref('chair', lazy='joined'), lazy='dynamic')
コード例 #8
0
ファイル: raspnagr.py プロジェクト: SevenLines/university-map
class Teacher(db.Model):
    __tablename__ = "prepods"
    id = db.Column('id_61', db.Integer, primary_key=True)
    full_name = db.Column('prep', db.String(100))
    name = db.Column('preps', db.String(50))

    raspnagr = db.relationship('Raspnagr', backref=db.backref('teacher', lazy='joined'), lazy='dynamic')
コード例 #9
0
ファイル: models.py プロジェクト: JiehuiSun/DataTools
class TasksLogModel(db.Model):
    """
    任务日志
    """
    __tablename__ = "tasks_log_model"

    id = db.Column(db.Integer, primary_key=True)
    ex_type = db.Column(db.Integer, comment="执行类型")
    task_no = db.Column(db.ForeignKey("tasks_model.id"))
    task = db.relationship('TasksModel',
                           backref=db.backref('tasks_log_model',
                                              lazy='dynamic'))
    return_info = db.Column(db.Text, nullable=True, comment="返回信息")
    dt_handled = db.Column(db.DateTime,
                           default=time_utils.now_dt,
                           comment="处理时间")
    is_successful = db.Column(db.Boolean, default=True, comment="是否成功")
    recipient = db.Column(db.Text, nullable=True, comment="收信人")
    file_name = db.Column(db.String(128), nullable=True, comment="文件名")
    is_deleted = db.Column(db.Boolean, default=False)
    dt_create = db.Column(db.DateTime, default=time_utils.now_dt)
    dt_update = db.Column(db.DateTime,
                          default=time_utils.now_dt,
                          onupdate=time_utils.now_dt)

    def __repr__(self):
        return str(self.task_no)

    def __str__(self):
        return str(self.id)
コード例 #10
0
ファイル: raspnagr.py プロジェクト: SevenLines/university-map
class Kontkurs(db.Model):
    id = db.Column('id_1', db.Integer, primary_key=True)
    title = db.Column("obozn")
    shup = db.Column(db.Integer)
    spclntion = db.Column(db.Integer)
    kurs = db.Column(db.Integer)
    fil = db.Column(db.Integer)
    fac_id = db.Column("fac", db.Integer, db.ForeignKey('vacfac.id_5'))
    aobozn_id = db.Column("aobozn", db.Integer, db.ForeignKey('vacaobozn.id_6'))
    stud = db.Column(db.Integer)
    groups = db.Column(db.Integer)
    pgroups = db.Column(db.Integer)
    smenao = db.Column(db.Integer)
    smenav = db.Column(db.Integer)
    groupkey = db.Column(db.Integer)
    undoworksps = db.Column(db.String(250))
    anothernumstudsps = db.Column(db.String(250))
    newnumstud = db.Column(db.SmallInteger)
    ntcgraph = db.Column(db.SmallInteger)
    syear = db.Column(db.Integer)

    groupslist = db.relationship('Kontgrp', backref='kontkurs', lazy='joined')
    kontlist = db.relationship('Kontlist', backref='kontkurs', lazy='select')
    raspnagr = db.relationship("Raspnagr", backref=db.backref('kontkurs', lazy='select'))

    def __str__(self, *args, **kwargs):
        return "<Kontkurs: {}>".format(self.title.strip())

    def __repr__(self):
        return str(self)

    def get_title(self):
        return self.title.replace("(И,О)", "")
コード例 #11
0
class Follow(db.Model):
    __tablename__ = "follows"
    id = db.Column(db.Integer, autoincrement=True, primary_key=True)

    follower_id = db.Column(db.Integer,
                            db.ForeignKey('users.id'),
                            nullable=False)
    followee_id = db.Column(db.Integer,
                            db.ForeignKey('users.id'),
                            nullable=False)

    follower = db.relationship('User',
                               backref=db.backref('followers', lazy=True),
                               foreign_keys=[follower_id])
    followee = db.relationship('User',
                               backref=db.backref('followees', lazy=True),
                               foreign_keys=[followee_id])
コード例 #12
0
class Article(db.Model):
    __tablename__ = 'articles'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255), nullable=False)
    content = db.Column(db.Text, nullable=False)
    created_at = db.Column(db.DateTime())
    updated_at = db.Column(db.DateTime())
    author = db.relationship('User', backref=db.backref('auth_users'))
    author_id = db.Column(db.Integer,
                          db.ForeignKey('auth_users.id'),
                          nullable=False)
    category = db.relationship('Category',
                               backref=db.backref('article_categories'))
    category_id = db.Column(db.Integer,
                            db.ForeignKey('article_categories.id'),
                            nullable=False)
    tags = db.Column(db.String(80), nullable=False)
    summary = db.Column(db.Text, nullable=False)
    view_num = db.Column(db.Integer, default=0)

    def __str__(self):
        return self.title
コード例 #13
0
ファイル: models.py プロジェクト: davidcmh/vault
class Note(db.Model):
    __tablename__ = 'notes'

    id = db.Column(db.Integer, primary_key=True)
    anki_id = db.Column(db.Integer)
    deck_id = db.Column(db.Integer, db.ForeignKey('decks.id'))
    deck = db.relationship('Deck', backref="notes")
    title = db.Column(db.String)
    content = db.Column(db.String)
    tags = db.relationship('Tag',
                           secondary=notes_tags_association,
                           lazy='subquery',
                           backref=db.backref('notes', lazy=True))
コード例 #14
0
class Conferencia(db.Model):
    id = db.Column(db.Integer, unique=True, primary_key=True)
    nombre = db.Column(db.String(200), unique=True)
    descripcion = db.Column(db.Text)
    fecha = db.Column(db.Text)
    precio = db.Column(db.Integer)
    sillas = db.relationship('Silla',
                             backref=db.backref('conferecias', lazy='dynamic'))

    def __init__(self, nombre, descripcion, fecha, precio):
        self.nombre = nombre
        self.descripcion = descripcion
        self.fecha = fecha
        self.precio = precio
コード例 #15
0
ファイル: raspnagr.py プロジェクト: SevenLines/university-map
class Kontgrp(db.Model):
    id = db.Column('id_7', db.Integer, primary_key=True)
    kont_id = db.Column("kont", db.Integer, db.ForeignKey('kontkurs.id_1'))
    title = db.Column("obozn", db.String(20))
    ngroup = db.Column(db.Integer)
    students = db.Column(db.Integer)
    parent_id = db.Column("parent", db.Integer, db.ForeignKey('kontgrp.id_7'))
    depth = db.Column(db.Integer)
    budzh = db.Column(db.Integer)
    spclntion = db.Column(db.Integer)

    op = db.relationship("Kontgrplist", backref=db.backref("kontgrp", lazy="joined"), lazy='joined')
    raspnagr = db.relationship("Raspnagr", backref=db.backref('kontgrp', lazy='joined'))
    children = db.relationship("Kontgrp", backref=db.backref('parent', remote_side=[id], lazy="joined"))

    def __str__(self, *args, **kwargs):
        return "<Kontgrp: {}>".format(self.title.strip())

    def __repr__(self):
        return str(self)

    def get_title(self):
        return self.title.replace("(И,О)", "")
コード例 #16
0
class Model(db.Model):
    __tablename__ = "model"

    id = Column(Integer, primary_key=True)
    make_id = Column(Integer, ForeignKey("make.id"))

    name = Column(String(50))

    #make           backref to Make
    badges = relationship("Badge",
                          backref=db.backref("model", uselist=False),
                          uselist=True)

    def Serialize(self, **kwargs):
        schema = ModelSchema(**kwargs)
        return schema.dump(self)

    def Create(make, model):
        result = Model(
            make_id         = make.id,              \
            name            = model["Model"])

        db.session.add(result)
        db.session.flush()

        if "Badges" in model:
            result.LoadBadges(model["Badges"])

        return result

    def LoadBadges(self, badges):

        for badge in badges:
            result = Badge.Create(self, badge)

            if not result:
                print("Failed to import a badge {0}!".format(badge["Badge"]))
                exit()

    def GetById(modelid):
        return Model.query                      \
            .filter(Model.id == modelid)        \
            .scalar()

    def __str__(self):
        return "<Model " + str(self.id) + ": " + self.name + ">"
コード例 #17
0
ファイル: models.py プロジェクト: davedavis/base
class Bookmark(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.Text, nullable=False)
    date = db.Column(db.DateTime, default=datetime.utcnow)
    description = db.Column(db.String(300))
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    # Set the relationship with the Tag class, need to use a string as it's not defined until later. ToDo: Move it up
    # and replace it with the class name for future proofing. The second argument to the relationship call is the
    # argument 'secondary' which tells the relationship to use our junction table called "tags" above. We also defined
    # a backref called 'bookmarks' which will add an attribute called bookmarks to the other side of the relationship.
    # So each tag will get a bookmarks attribute containing a list of the associated bookmarks. Dynamic loading in case
    # there are a large number of bookmarks associated with each tag.
    # Underscore as I don't want to access this directly from other classes.
    _tags = db.relationship('Tag', secondary=tags, lazy='joined', backref=db.backref('bookmarks', lazy='dynamic'))

    @staticmethod
    def newest(num):
        return Bookmark.query.order_by(desc(Bookmark.date)).limit(num)

    # In the view and the form, we handle the list of tags as a comma separated string. So it's convenient to create a
    # tag property that provides a list of strings as well. The getter takes the contents of the _tags list which holds
    # actual Tag model objects. Then it takes the name from each and joins it into a string. So when we ask for the
    # value of the tags property on a bookmark, we get a string, with a list of tag names.
    @property
    def tags(self):
        return ",".join([t.name for t in self._tags])

    # When we pass a string with a list of tags to be set to this property, we need to find out for each of those tags
    # whether it already exists in the database. If it doesn't, we need to insert a new tag into the tag table and then
    # add the new model object to the tag list for this bookmark. If it does exist, we can simply retrieve it and put it
    # in the list. So if it exists, we create a new method get_or_create that takes the name of a tag and returns a tag
    # model instance by either creating or retrieving a tag with that name. We then do a for loop over all the words in
    # the string we received and then call the method on each of those words. The resulting list is a list of tag model
    # objects and we can assign that to the _tags attribute. Assigning a list of tag objects is all we have to do and
    # SQLAlchemy will take it from there and create all the relevant rows in the database.
    @tags.setter
    def tags(self, string):
        # Check if the tags are a string
        if string:
            self._tags = [Tag.get_or_create(name) for name in string.split(',')]
        # If not, set the list ot an empty list, otherwise, it will always fail the test.
        else:
            self._tags = []

    def __repr__(self):
        return "Bookmark '{}': '{}'>".format(self.description, self.url)
コード例 #18
0
ファイル: models.py プロジェクト: JiehuiSun/DataTools
class TasksModel(db.Model):
    """
    任务
    """
    __tablename__ = "tasks_model"

    id = db.Column(db.Integer, primary_key=True)
    task_no = db.Column(db.String(128),
                        nullable=False,
                        default=gen_task_no,
                        comment="备注")
    task_type = db.Column(db.Enum('cron', 'interval', 'date'),
                          server_default='cron',
                          nullable=False)
    name = db.Column(db.String(128), nullable=False, comment="任务名")
    project_id = db.Column(db.ForeignKey("requirement_model.id"))
    project = db.relationship('RequirementModel',
                              backref=db.backref('tasks_model',
                                                 lazy='dynamic'))
    comments = db.Column(db.String(256), nullable=True, comment="备注")
    year = db.Column(db.Integer, nullable=True, comment="年")
    month = db.Column(db.Integer, nullable=True, comment="月")
    day = db.Column(db.Integer, nullable=True, comment="日")
    week = db.Column(db.Integer, nullable=True, comment="周")
    day_of_week = db.Column(db.Integer, nullable=True, comment="周期")
    hour = db.Column(db.Integer, nullable=True, comment="时")
    minute = db.Column(db.Integer, nullable=True, comment="分")
    second = db.Column(db.Integer, nullable=True, comment="秒")
    status = db.Column(db.Boolean, default=False, comment="状态")
    is_deleted = db.Column(db.Boolean, default=False)
    dt_create = db.Column(db.DateTime, default=time_utils.now_dt)
    dt_update = db.Column(db.DateTime,
                          default=time_utils.now_dt,
                          onupdate=time_utils.now_dt)

    def __repr__(self):
        return self.name

    def __str__(self):
        return self.name
コード例 #19
0
ファイル: raspnagr.py プロジェクト: SevenLines/university-map
class Obozn(db.Model):
    __tablename__ = "vacaobozn"
    id = db.Column('id_6', db.Integer, primary_key=True)
    title = db.Column("aobozn", db.String(50))

    kontkurs = db.relationship("Kontkurs", backref=db.backref("aobozn", lazy="joined"))
コード例 #20
0
class Tweet(db.Model):
    __tablename__ = "tweets"
    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    text = db.Column(db.String(140), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    user = db.relationship('User', backref=db.backref('tweets', lazy=True))
コード例 #21
0
ファイル: raspnagr.py プロジェクト: SevenLines/university-map
class Faculty(db.Model):
    __tablename__ = "vacfac"
    id = db.Column('id_5', db.Integer, primary_key=True)
    title = db.Column("fac", db.String(65))

    kontkurs = db.relationship('Kontkurs', backref=db.backref('faculty', lazy='joined'), lazy='dynamic')
コード例 #22
0
class Comment(FullText, db.Model):
    """
    This class is here because comments can only be made on threads,
    so it is contained in the threads module.

    Note the parent_id and children values. A comment can be commented
    on, so a comment has a one to many relationship with itself.

    Backrefs:
        A comment can refer to its parent thread with 'thread'
        A comment can refer to its parent comment (if exists) with 'parent'
    """
    __tablename__ = 'threads_comment'
    __fulltext_columns__ = ('text', )
    id = db.Column(db.Integer, primary_key=True)
    text = db.Column(db.String(THREAD.MAX_BODY), default=None)

    user_id = db.Column(db.Integer, db.ForeignKey('users_user.id'))
    thread_id = db.Column(db.Integer, db.ForeignKey('threads_thread.id'))

    parent_id = db.Column(db.Integer, db.ForeignKey('threads_comment.id'))
    children = db.relationship('Comment',
                               backref=db.backref('parent', remote_side=[id]),
                               lazy='dynamic')

    depth = db.Column(db.Integer, default=1)  # savet at depth 1

    created_on = db.Column(db.DateTime, default=now)
    updated_on = db.Column(db.DateTime, default=now)

    votes = db.Column(db.Integer, default=1)

    @reconstructor
    def setup_fields(self):
        self.text = format_comment(self.text)

    def __repr__(self):
        return '<Comment %r>' % (self.text[:25])

    def set_depth(self):
        """
        call after initializing
        """
        if self.parent:
            self.depth = self.parent.depth + 1
            db.session.commit()

    def get_comments(self, order_by='votes'):
        """
        default order by votes
        """
        if order_by == 'votes':
            return self.children.order_by(db.desc(Comment.votes)).\
                all()[:THREAD.MAX_COMMENTS]
        elif order_by == 'timestamp':
            return self.comments.order_by(db.desc(Comment.votes)).\
                all()[:THREAD.MAX_COMMENTS]

    def pretty_date(self, typeof='created'):
        """
        returns a humanized version of the raw age of this thread,
        eg: 34 minutes ago versus 2040 seconds ago.
        """
        if typeof == 'created':
            logger.info(arrow.get(self.created_on, 'UTC'))
            logger.info(arrow.get(self.created_on, 'UTC').humanize())
            return arrow.get(self.created_on, 'UTC').humanize()
        elif typeof == 'updated':
            return arrow.get(self.updated_on, 'UTC').humanize()

    def has_voted(self, user_id):
        select_votes = comment_upvotes.select(
            db.and_(comment_upvotes.c.user_id == user_id,
                    comment_upvotes.c.comment_id == self.id))
        rs = db.engine.execute(select_votes)
        return False if rs.rowcount == 0 else True

    def vote(self, user_id):
        """
            Add a vote from user id to a comment.
        """
        already_voted = self.has_voted(user_id)
        vote_status = None
        if not already_voted:
            # vote up the thread
            db.engine.execute(comment_upvotes.insert(),
                              user_id=user_id,
                              comment_id=self.id)
            self.votes = self.votes + 1
            vote_status = True
        else:
            # unvote the thread
            db.engine.execute(
                comment_upvotes.delete(
                    db.and_(comment_upvotes.c.user_id == user_id,
                            comment_upvotes.c.comment_id == self.id)))
            self.votes = self.votes - 1
            vote_status = False
        db.session.commit()  # for the vote count
        return vote_status

    def comment_on(self):
        """
        when someone comments on this particular comment
        """
        pass
コード例 #23
0
class Make(db.Model):
    __tablename__ = "make"

    id = Column(Integer, primary_key=True)
    type_ = Column(String(10))
    name = Column(String(50))

    models = relationship("Model",
                          backref=db.backref("make", uselist=False),
                          uselist=True)

    __mapper_args__ = {"polymorphic_identity": "make", "polymorphic_on": type_}

    def Serialize(self, **kwargs):
        schema = MakeSchema(**kwargs)
        return schema.dump(self)

    def LoadModels(self, models):
        for model in models:
            result = Model.Create(self, model)

            if not result:
                print("Failed to import a model {0}!".format(model["Model"]))
                exit()

    # Finds all Make records of type 'type' and returns them, where applicable,
    # as an instance of their derived type.
    def GetByType(type):
        return with_polymorphic(Make, "*").query        \
            .filter(Make.type_ == type)                 \
            .all()

    # Finds the Make record associated with makeid, but returns it with a parent-child relationship
    # between Make and a derived type (if any.)
    # -> Make.GetById( x )
    # <- (Car<x>)
    def GetById(makeid):
        return with_polymorphic(Make, "*").query        \
            .filter(Make.id == makeid)                  \
            .scalar()

    @hybrid_property
    def num_models(self):
        return len(self.models)

    @hybrid_property
    def num_badges(self):
        total = 0

        for x in self.models:
            total += len(x.badges)
        return total

    # Type sensitive hybrid methods.
    # Remember to call on the Class level of a child.

    # Creates a new table based on the derived type for each item in makes.
    # Then generates that makes models, and that models badges (if applicable.)
    # If you define a new type and have custom create logic, you'll need to override this.
    @hybrid_method
    def Create(cls, makes):

        for make in makes:
            if cls.Exists(make["Make"]):
                continue

            result = cls(name=make["Make"])

            db.session.add(result)
            db.session.flush()

            result.LoadModels(make["Models"])

            if not result:
                print("Failed to import type: {0}!".format(cls.__table__.name))
                exit()

        return True

    # Finds a [ Car/Bike, Model, Badge (if applic.) ] set based on make, model and badge.
    # Can return multiple results. Particularly if you provide no badge.
    # Always returns in the form of a list for consistency. Ensure you do your len() as you may not always get a Badge.
    # ( Toyota, Supra ) would return SZ, RZ, SZ-R etc.
    @hybrid_method
    def Find(cls, make, model, badge=None):
        query = db.session.query(cls, Model, Badge)                                     \
            .join(Model, Model.make_id == cls.id)                                       \
            .outerjoin(Badge, Badge.model_id == Model.id)                               \
                                                                                        \
            .filter(cls.name == make)                                                   \
            .filter(Model.name == model)                                                \
            .filter(or_(Badge.name == badge, or_(badge == None, Badge.name == None)))   \
            .filter(cls.type_ == cls.__table__.name)

        return query.all()

    # Checks whether any make record exists where attached to the type of cls.
    @hybrid_method
    def Exists(cls, name):
        return cls.query                                \
            .filter(cls.name == name)                   \
            .filter(cls.type_ == cls.__table__.name)    \
            .scalar()
コード例 #24
0
ファイル: raspnagr.py プロジェクト: SevenLines/university-map
class Raspnagr(db.Model):
    id = db.Column('id_51', db.Integer, primary_key=True)
    kontkurs_id = db.Column("kont", db.Integer, db.ForeignKey('kontkurs.id_1'))
    kontgrp_id = db.Column("kontid", db.Integer, db.ForeignKey('kontgrp.id_7'))
    op = db.Column("op", db.Integer)
    nt = db.Column(db.Integer, db.ForeignKey("normtime.id_40"))
    sem = db.Column(db.Integer)
    pred_id = db.Column("pred", db.Integer, db.ForeignKey("vacpred.id_15"))
    kaf_id = db.Column("kaf", db.Integer, db.ForeignKey("vackaf.id_17"))
    fobuch = db.Column(db.SmallInteger)
    afobuch = db.Column(db.SmallInteger)
    nagrid = db.Column(db.Integer)
    h = db.Column(db.Float)
    hy = db.Column(db.Integer)
    dbeg = db.Column(db.Date)
    days = db.Column(db.Integer)
    prep_id = db.Column("prep", db.Integer, db.ForeignKey('prepods.id_61'))
    aud_id = db.Column("aud", db.Integer, db.ForeignKey('auditories.id_60'))
    nagrtype = db.Column(db.SmallInteger)
    nagrprop = db.Column(db.Integer)
    nagr_h = db.Column(db.Float)
    stud = db.Column(db.Integer)
    editstud = db.Column(db.Integer)
    rnprep = db.Column(db.Integer)
    # hy1 = db.Column(db.Integer)
    # hy2 = db.Column(db.Integer)
    syear = db.Column(db.Integer)

    raspis = db.relationship('Raspis', backref=db.backref('raspnagr', lazy='joined'), lazy='dynamic')
    raspis_zaoch = db.relationship('RaspisZaoch', backref=db.backref('raspnagr', lazy='joined'), lazy='dynamic')
    kontlist = db.relationship('Kontlist', backref='raspnagr', lazy='subquery')
    kontgrplist = db.relationship('Kontgrplist', backref='raspnagr', lazy='subquery')

    @classmethod
    def get_for_kontgrp(self, kontgrp):
        raspnagrs = Raspnagr.query.filter(
            or_(Raspnagr.kontgrp_id == kontgrp.id, Raspnagr.kontkurs_id == kontgrp.kont_id)
        )
        return raspnagrs

    @classmethod
    def get_for_kontkurs_id(self, kontkurs_id, sem=1, subgroup_number=0):
        Kontgrp2 = aliased(Kontgrp)
        KontgrpCommon = aliased(Kontgrp)
        KontgrpParent = aliased(Kontgrp)

        if not isinstance(kontkurs_id, list):
            kontkurs_id = [kontkurs_id, ]

        if int(subgroup_number):
            filter_ = and_(or_(
                Raspnagr.kontkurs_id.in_(kontkurs_id),
                Kontlist.kontkurs_id.in_(kontkurs_id),
                KontgrpCommon.kont_id.in_(kontkurs_id),
            ), or_(
                KontgrpCommon.id == None,
                and_(KontgrpParent.id == None, KontgrpCommon.ngroup == subgroup_number),
                KontgrpParent.ngroup == subgroup_number
            ), )
        else:
            filter_ = or_(
                Raspnagr.kontkurs_id.in_(kontkurs_id),
                KontgrpCommon.kont_id.in_(kontkurs_id),
                Kontlist.kontkurs_id.in_(kontkurs_id),
            )

        raspnagrs = Raspnagr.query.filter(
            Raspnagr.id.in_(Raspnagr.query
                            .outerjoin(Kontgrp, Raspnagr.kontgrp_id == Kontgrp.id)
                            .outerjoin(Kontgrplist, Kontgrplist.op == Raspnagr.op)
                            .outerjoin(Kontlist, Kontlist.op == Raspnagr.op)
                            .outerjoin(Kontgrp2, Kontgrp2.id == Kontgrplist.kontgrp_id)
                            .outerjoin(KontgrpCommon, func.coalesce(Kontgrp2.id, Kontgrp.id) == KontgrpCommon.id)
                            .outerjoin(KontgrpParent, KontgrpCommon.parent_id == KontgrpParent.id)
                            .filter(filter_).filter(Raspnagr.sem == sem).with_entities(Raspnagr.id)))
        return raspnagrs