python - 一对一关系数据库模型不起作用

标签 python sqlalchemy flask-sqlalchemy

背景:

我有一个项目,用户可以上传文件。在数据库中,我想存储上传文件的文件路径。

数据库中有2个表; a UsersFileUploadPath。这些表具有一对一的关系。

我目前拥有的 Flask-SQLAlchemy 模型是:

import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////{}'.format(os.path.join(os.getcwd(), "test.db"))
db = SQLAlchemy(app)


class User(db.Model):

    __tablename__ = 'Users'

    userid = db.Column(db.Integer, primary_key=True, autoincrement=True)
    fname = db.Column(db.String(80), nullable=False)
    lname = db.Column(db.String(80), nullable=False)
    phonenum = db.Column(db.String(10), nullable=False)
    email = db.Column(db.String(60), nullable=False)
    password = db.Column(db.String(60), nullable=False)
    validated = db.Column(db.Boolean, default=False)

    child = db.relationship('FileUploadPath', uselist=False, backref='Users')


class FileUploadPath(db.Model):

    __tablename__ = 'FileUploadPath'

    fileUploadID = db.Column(db.Integer, primary_key=True, autoincrement=True)
    w9FilePath = db.Column(db.String(60), nullable=False)
    gcFilePath = db.Column(db.String(60), nullable=False)
    livescanFilePath = db.Column(db.String(60), nullable=False)
    gcaFilePath = db.Column(db.String(60), nullable=False)

    userID = db.Column(db.Integer, db.ForeignKey('Users.userid'))

要创建新用户,我使用以下命令:

newuser = User(fname='Bob', lname='Smith', phonenum='6551234567', email='bobsmith@gmail.com', password='fe287943hfbwiqey281')

使用此命令,我希望在 FileUploadPath 表中看到一个 userID;目前在 Users 表中仅看到创建的用户,但在 userID 列中看到 NULL

通过查询,我还想查看与特定用户相关的所有上传文件路径信息。

模型设置之间的关系是否正确?如果不是,我该如何声明这种关系?

编辑:

我想要做的是将fileUploadID存储在Users表中。应为创建的每个新用户插入 FileUploadPath 表中的新行。因为当我创建一个新用户时,FileUploadPath 表中的所有列都将为空;因为新用户尚未上传任何文件。

最佳答案

表关系看起来不错,只是 backref='Users' 的名称选择很奇怪,因为这会向 FileUploadPath 添加一个“Users”属性,它不遵循其其余属性的命名约定。我本来希望它是 backref='user'

现在,主要问题是您没有指定 newuser 应该关联的 FileUploadPath,因此它没有在 中插入任何条目FileUploadPath 引用 newuser 的 ID。或者,您可能已经插入了一个新的 FileUploadPath,您打算将其链接到 newuser,尽管您没有在示例中显示该代码。在任何情况下,它都不知道哪个 FileUploadPath 与哪个 User 关联,并且它不会自动为每个用户创建一个新的 FileUploadPath User,因此当您仅创建一个新的 User 时,或者如果您单独创建新的 UserFileUploadPath 但不要链接它们,您最终不会得到与新 User 关联的 FileUploadPath

因此,您需要做的就是通过添加 child=newFileUploadPath 参数(其中 >newFileUploadPath 是已构造的 FileUploadPath 对象),当您调用 User 构造函数时,或者通过单独构造并添加 UserFileUploadPath 对象,并设置 newuser.child = newFileUploadPathnewFileUploadPath.user = newuser。 (请注意,newFileUploadPath.user 假定我建议的 backref='user' 更改。)

编辑:这是一个MVCE,展示了如何为用户添加文件上传。但是,在最初创建用户时,文件上传并不存在,这应该是预期的行为。 FileUploadPath 中绝对不应该有包含所有空字符串的条目。此外,如果您计划允许每个用户最多上传 4 次,则需要通过删除 uselist=False 并处理 Users 来使其成为多对一关系。 child 作为列表,也可以将其重命名为 childrenuploads

(请注意,此示例使用普通 SQLAlchemy 而不是 Flask-SQLAlchemy,因此模型定义和数据库设置的某些部分可能与您的实现不同。)

import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy import create_engine

Base = declarative_base()

class User(Base):
    __tablename__ = 'Users'

    userid = Column(Integer, primary_key=True, autoincrement=True)
    fname = Column(String(80), nullable=False)
    lname = Column(String(80), nullable=False)
    phonenum = Column(String(10), nullable=False)
    email = Column(String(60), nullable=False)
    password = Column(String(60), nullable=False)
    validated = Column(Boolean, default=False)

    child = relationship('FileUploadPath', uselist=False, backref='user')


class FileUploadPath(Base):
    __tablename__ = 'FileUploadPath'

    fileUploadID = Column(Integer, primary_key=True, autoincrement=True)
    w9FilePath = Column(String(60), nullable=False)
    gcFilePath = Column(String(60), nullable=False)
    livescanFilePath = Column(String(60), nullable=False)
    gcaFilePath = Column(String(60), nullable=False)

    userID = Column(Integer, ForeignKey('Users.userid'))

engine = create_engine('sqlite:///')
Base.metadata.create_all(engine)
session_factory = sessionmaker(bind=engine)
session = session_factory()

# Insert a new user with no uploads:
newuser = User(fname='Bob', lname='Smith', phonenum='6551234567', email='bobsmith@gmail.com', password='fe287943hfbwiqey281')
session.add(newuser)
session.commit()

# Query for users and uploads:
print(session.query(FileUploadPath).count())
# 0

print(session.query(User).count())
# 1

print(session.query(User).one().child)
# None

# Insert an upload for the user:
newupload = FileUploadPath(w9FilePath='some_path', gcFilePath='another_path', livescanFilePath='yet_another_path', gcaFilePath='another_path_still', user=newuser)
session.add(newupload)
session.commit()

# Again, query for users and uploads:
print(session.query(FileUploadPath).count())
# 1

print(session.query(User).one().child)
# <FileUploadPath object>

print(session.query(User).one().child.w9FilePath)
# 'some_path'

关于python - 一对一关系数据库模型不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49020321/

相关文章:

python - SQLAlchemy __init__ 未运行

python - 如何将行插入表 sqlalchemy 对象?

python - flask 中有没有办法获取 request.json 中的每个对象并将每个属性保存在模型上?

c++ - 使用 boost.python 时 c++ 流有什么问题?

python,帮助替换第一个字母

python - 如何在虚拟环境中使用 pip

python - 检查给定内存地址处的对象

python - 默认检查同一个表的列

python - SQLite Date 类型仅接受 Python 日期对象作为输入

python - 如何使用目录 api 和 python 将成员添加到组中?