首页 > 数据库 >sqlalchemy_one2many_一对多

sqlalchemy_one2many_一对多

时间:2023-02-19 21:56:31浏览次数:42  
标签:sqlalchemy title one2many session User Post 一对 id user

sqlalchemy_one_to_many_relationship-main/delete.py

from main import Post,User,session


print(session.query(Post).all())
print(session.query(User).all())


# 删除这个user,呢么在post表里面所有关于这个user的数据也会被删除
# posts=relationship('Post',back_populates='author',cascade='all, delete')
user_to_delete=session.query(User).filter(User.id==1).first()
session.delete(user_to_delete)
session.commit()


print(session.query(Post).all())
print(session.query(User).all())

# output:---------------------------------------------------------------------
# => (venv) song@songdembp@ sqlalchemy_one_to_many_relationship-main % python delete.py 
# => [<User Learn Django>, <User Learn Java>, <User Learn Javascript>, <User Learn HTML>, <User Learn css>]
# => [<User testuser>]
# => []
# => []```
# `sqlalchemy_one_to_many_relationship-main/query.py`

```py
from main import Post,User,session

# ----------------------------------------------------------------------------------
# 查询所有的 user.id ==1,的post
# class User(Base):
#     __tablename__='users'
#     id=Column(Integer(),primary_key=True)
#     username=Column(String(40),nullable=False)
#     email=Column(String(40),nullable=True)

#     posts=relationship('Post',back_populates='author',cascade='all, delete')

user=session.query(User).filter(User.id==1).first()
# posts变成user的一个属性,直接打印就行,就是得出结果,不需要在到数据中使用select * from post where id == user.id,类似的语句,直接使用就行
print(user.posts)



# ----------------------------------------------------------------------------------
# 同理,查询author的时候,也是直接查询,通过属性形式
# class Post(Base):
#     __tablename__='posts'
#     id=Column(Integer(),primary_key=True)
#     title=Column(String(45),nullable=False)
#     content=Column(String(255),nullable=False)
#     user_id=Column(Integer(),ForeignKey('users.id'))

#     author=relationship('User',back_populates='posts')
post=session.query(Post).filter(Post.id==1).first()
print(post)
print(post.author)

# --------------------------------------------------------------------------------------------------
# 关键的几行代码:

# class User(Base):
#     posts=relationship('Post',back_populates='author',cascade='all, delete')

# class Post(Base):
#     author=relationship('User',back_populates='posts')

sqlalchemy_one_to_many_relationship-main/query copy.py

from main import Post,User,session


new_user=User(
    username="testuser",
    email="[email protected]"
)

session.add(new_user)
session.commit()


posts=[
    {
        "title":"Learn Django",
        "content":"Lorem ipsum"
    },
      {
        "title":"Learn Java",
        "content":"Lorem ipsum"
    },
      {
        "title":"Learn Javascript",
        "content":"Lorem ipsum"
    },
      {
        "title":"Learn HTML",
        "content":"Lorem ipsum"
    },
      {
        "title":"Learn css",
        "content":"Lorem ipsum"
    },

]

user=session.query(User).filter(User.id==1).first()


# for post in posts:
#     new_post=Post(
#         title=post['title'],
#         content=post['content'],
#         author=user
#     )

#     session.add(new_post)
#     session.commit()

#     print(f"Post cREATED {post['title']}")


post=session.query(Post).filter(Post.id==1).first()
print(post.author)
print(user.posts)```
# `sqlalchemy_one_to_many_relationship-main/main.py`

```py
#user
#posts
import os
from sqlalchemy import (
    create_engine,
    Integer,
    Column,
    String,
    ForeignKey
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship,sessionmaker


BASE_DIR=os.path.dirname(os.path.realpath(__file__))

conn='sqlite:///'+os.path.join(BASE_DIR,'blog.db')


engine=create_engine(conn)


Base=declarative_base()


"""
class User:
    id:int pk
    username:str
    email:str


class Post:
    id:int pk
    title:str
    content:str
    user_id:int foreignkey
"""


class User(Base):
    __tablename__='users'
    id=Column(Integer(),primary_key=True)
    username=Column(String(40),nullable=False)
    email=Column(String(40),nullable=True)
    posts=relationship('Post',back_populates='author',cascade='all, delete')

    def __repr__(self):
        return f"<User {self.username}>"

class Post(Base):
    __tablename__='posts'
    id=Column(Integer(),primary_key=True)
    title=Column(String(45),nullable=False)
    content=Column(String(255),nullable=False)
    user_id=Column(Integer(),ForeignKey('users.id'))

    author=relationship('User',back_populates='posts')


    
    def __repr__(self):
        return f"<User {self.title}>"


Base.metadata.create_all(engine) #creates the database

session=sessionmaker()(bind=engine)

sqlalchemy_one_to_many_relationship-main/populate.py

from main import Post,User,session


new_user=User(
    username="testuser",
    email="[email protected]"
)

session.add(new_user)
session.commit()


posts=[
    {
        "title":"Learn Django",
        "content":"Lorem ipsum"
    },
      {
        "title":"Learn Java",
        "content":"Lorem ipsum"
    },
      {
        "title":"Learn Javascript",
        "content":"Lorem ipsum"
    },
      {
        "title":"Learn HTML",
        "content":"Lorem ipsum"
    },
      {
        "title":"Learn css",
        "content":"Lorem ipsum"
    },

]


user=session.query(User).filter(User.id==1).first()

# class Post(Base):
#     __tablename__='posts'
#     id=Column(Integer(),primary_key=True)
#     title=Column(String(45),nullable=False)
#     content=Column(String(255),nullable=False)
#     user_id=Column(Integer(),ForeignKey('users.id'))
#     author=relationship('User',back_populates='posts')



for post in posts:
    new_post=Post(
        title=post['title'],
        content=post['content'],
        author=user
    )

    session.add(new_post)
    session.commit()

    print(f"Post cREATED {post['title']}")


生成的数据表

img

标签:sqlalchemy,title,one2many,session,User,Post,一对,id,user
From: https://www.cnblogs.com/zhuoss/p/17135690.html

相关文章

  • springboot mybatis (关联关系:一对一,一对多,多对多)
    例如这个学生选课的这个:这个里面课程跟老师是1对1的,而老师对课程是1对多的,一个课程只能由一个老师教,而一个老师可以教多个课程对于学生和课程之间是多对多的,一个学生可以......
  • sqlalchemy_装饰器获取session
    /Users/codelearn/fastapi-tutorial-fastapi_with_async_sqlalchemy/run.py#uvicornbackend.app.main:app--host127.0.0.1--port8000#uvicornsrc.main:app--hos......
  • Hibernate annotation 一对多,多对一
     packagecom.hibernate.entity;importjava.io.Serializable;@EntitypublicclassTgroupimplementsSerializable{/****/privatestaticfinallongse......
  • fastapi_sqlalchemy_mysql_rbac_jwt_gooddemo
    /Users//codelearn/fastapi_sqlalchemy_mysql_01/init_test_data.py#!/usr/bin/envpython3#-*-coding:utf-8-*-importasynciofromemail_validatorimportEmai......
  • 一封传话一对多推送实现步骤
    前言前面介绍了一封传话聚合推送API的在线测试推送的步骤,可以实现一对一发送消息。但是我们希望实现:1.群组订阅功能:例如我和我的好友一起加入通道后,只推送一次我们两个......
  • 10.1 汇编语言和本地代码是一一对应的
    在加法运算的本地代码中加上add(addition的缩写)、在比较运算的本地代码中加上cmp(compare的缩写)等。这些缩写称为助记符,使用助记符的编程语言称为汇编语言。通过查看汇编......
  • 一封传话一对多推送实现步骤
    前言前面介绍了一封传话聚合推送API的在线测试推送的步骤,可以实现一对一发送消息。但是我们希望实现:1.群组订阅功能:例如我和我的好友一起加入通道后,只推送一次我们两个......
  • Mybatis11 - 一对多
    一次查询,通过部门id查询部门信息以及该部门所有员工信息方法一:resultMap中使用collection标签,专门处理实体类集合属性的一对多关系接口类方法DeptgetDeptAndEmpBy......
  • Mybatis使用注解实现一对多复杂关系映射
    一、问题引入:查询用户信息时,将用户的所有账户也查询出来,使用注解方式实现(一个账户具有多个用户信息,所以形成了用户和账户之间的一对多关系)account表user表:二......
  • Mybatis使用注解实现一对一复杂关系映射及延迟加载
    一、问题引入:在加载账户信息时同时加载该账户的用户信息,根据情况可实现延时加载(注解方式实现)数据库字段如下:user表:account表:二、添加User实体类和Account类us......