zoukankan      html  css  js  c++  java
  • 三种排序方式

    #encoding: utf-8
    
    from sqlalchemy import create_engine,Column,Integer,String,Float,func,and_,or_,Text,
        ForeignKey,DateTime
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker,relationship,backref
    from random import randint
    from datetime import datetime
    
    HOSTNAME = '127.0.0.1'
    
    PORT = 3306
    
    DATABASE = 'first_sqlalchemy'
    
    USERNAME = 'root'
    
    PASSWORD = '123456'
    
    #dialect+driver://username:password@host:port/database
    DB_URI = "mysql+pymysql://{username}:{password}@{host}:{port}/" 
             "{db}?charset=utf8".format(username=USERNAME,password=PASSWORD,host=HOSTNAME,port=PORT,db=DATABASE)
    
    engine = create_engine(DB_URI)
    
    Base = declarative_base(engine)
    
    # Session = sessionmaker(engine)
    # session = Session()
    
    session = sessionmaker(engine)() #Session(**local_kw)
    
    #第三种排序方式根据一对多,多对对关系,进行排序,排序只能作用在多的关系上,
    
    
    class User(Base):
        __tablename__ = 'user'
        id = Column(Integer, primary_key=True, autoincrement=True)
        username = Column(String(50),nullable=False)
    
    class Article(Base):
        __tablename__ = 'article'
        id = Column(Integer,primary_key=True,autoincrement=True)
        title = Column(String(50),nullable=False)
        create_time = Column(DateTime,nullable=False,default=datetime.now)#datetime.now不能加括号,是文章生成插入数据库的时间
        uid = Column(Integer,ForeignKey('user.id'))
        #第三种排序方式,跟relationship结合使用,作用多的关系上
        author = relationship("User",back_ref=backref('articles',order_by=create_time.desc()))
        #第二种排序方式,使用魔术属性
        __mapper_args__ = {
            "order_by": create_time.desc()
        }
    
        def __repr__(self):
            return '<article:{0},create_time:{1}>'.format(self.title,self.create_time)
    # Base.metadata.drop_all()
    # Base.metadata.create_all()
    
    # article = Article(title='123456')
    # session.add(article)
    # session.commit()
    
    #一个order_by根据文章的发表时间进行查询
    #字段前没有减号(-)就是升序排列
    #字段前有减号(-)就是降序排列
    # article = session.query(Article).order_by(-Article.create_time).all()
    #或使用desc,来倒序
    # article = session.query(Article).order_by(-Article.create_time.desc).all()
    #或用字段名来倒叙
    # article = session.query(Article).order_by("-create_time").all()
    # print(article)
    """
    SELECT article.id AS article_id, article.title AS article_title,
    article.create_time AS article_create_time 
    FROM article ORDER BY article.create_time
    """
    
    #使用第二种排序方式试一试
    articles = session.query(Article).all()
    print(articles)#测试是可以的
  • 相关阅读:
    R vs Python:构建data.frame、读取csv与统计描述
    R语言学习笔记:使用reshape2包实现整合与重构
    Python学习笔记:lambda表达式
    Python学习笔记:startswith & endswith 判断开头结尾是否为指定字符串
    Python学习笔记:一手漂亮的Python函数
    电信行业数据挖掘分析
    Oracle学习笔记:实现select top N的方法
    Oracle学习笔记:ORA-22992 cannot use LOB locators selected from remote tables
    Linux学习笔记:ls和ll命令
    vb常用命名空间
  • 原文地址:https://www.cnblogs.com/wuheng-123/p/9712137.html
Copyright © 2011-2022 走看看