flask中orm的一对多,多对多用法

# -*- coding: utf-8 -*-
"""
Author: 田野
Data: 2019-06-05 16:43
Introduction:
"""
from datetime import datetime
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:root@127.0.0.1/sqtest'
db = SQLAlchemy(app)


class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80))
    body = db.Column(db.Text)
    pub_date = db.Column(db.DateTime)

    category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
    category = db.relationship('Category',
                               backref=db.backref('posts', lazy='dynamic'))

    def __init__(self, title, body, category, pub_date=None):
        self.title = title
        self.body = body
        if pub_date is None:
            pub_date = datetime.utcnow()
        self.pub_date = pub_date
        self.category = category

    def __repr__(self):
        return '<Post %r>' % self.title


class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '<Category %r>' % self.name


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.username


@app.route('/')
def index():
    return 'hello world'


def add():
    '''新增'''
    admin = User('admin', 'admin@example.com')
    guest = User('guest', 'guest@example.com')
    db.session.add(admin)
    db.session.add(guest)
    db.session.commit()


def searchAll():
    users = User.query.all()
    admin = User.query.filter_by(username='admin').first()
    print(users)
    print(admin)


'''Person/Address 一对多'''


class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    addresses = db.relationship('Address', backref='person',
                                lazy='dynamic')

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return self.name


class Address(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    address = db.Column(db.String(50))
    person_id = db.Column(db.Integer, db.ForeignKey('person.id'))

    def __init__(self, address, person_id):
        self.address = address
        self.person_id = person_id

    def __repr__(self):
        return self.address


'''Page 和Tag多对多关系'''
account_site = db.Table('account_site',
                        db.Column('account_id', db.Integer, db.ForeignKey('account.id')),
                        db.Column('site_id', db.Integer, db.ForeignKey('site.id'))
                        )


class Account(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128))

    def __init__(self, name):
        self.name = name

    relate_courses = db.relationship('Site', secondary=account_site,
                                     backref='relate_student',
                                     lazy='dynamic')

    def __repr__(self):
        return self.name


class Site(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128))

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return self.name


if __name__ == '__main__':
    # a = Site('daA')
    # b= Site('daB')
    # c = Site('daC')
    # db.session.add_all([a,b,c])
    # db.session.commit()
    '''多对多查询'''
    # account = Account.query.filter_by(id=6).first()
    # print(account.relate_courses.all())
    site = Site.query.filter_by(id=1).first()
    print(site.relate_student)

    # app.run(debug=True)
    # add()
    # searchAll()
    # py = Category('Python')
    # p = Post('Hello Python!', 'Python is pretty cool', py)
    # db.session.add(py)
    # db.session.add(p)
    '''新增'''
    # person = Person('tianye2010@foxmail.com','钟楼')
    # db.session.add(person)
    # db.session.commit()
    # address = Address('回民街2',2)
    # db.session.add(address)
    # db.session.commit()
    # account = Account.query.filter(Account.name=='aaaa')
    # db.session.add(account)
    # db.session.commit()
    # print(account.id)
    # db.session.delete(account)
    # db.session.commit()
    # account = Account('bbbb')
    # db.session.add(account)
    # db.session.commit()
    # account = Account('cccc')
    # db.session.add(account)
    # account = Account('dddd')
    # db.session.add(account)
    # site = Site('dulizhan')
    # db.session.add(site)
    # sit = Site('云站')
    # db.session.add(site)
    # sit = Site('shopify')
    # db.session.add(site)
    # sit = Site('erp')
    # db.session.add(site)
    # db.session.commit()
    '''一对多查询'''
    # 一查多
    # person = Person.query.filter_by(id=1).first()
    # print(person.addresses.all())
    # 多查一
    # address = Address.query.filter_by(address='回民街').first()
    # print(address.person)
    '''多对多查询'''

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值