Compare commits
12 Commits
main
...
pr/maru012
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00b30c65c9 | ||
|
|
9509313eaf | ||
|
|
a1833901f5 | ||
|
|
54d1816a9f | ||
|
|
c4c58cc2be | ||
|
|
8fa01150f4 | ||
|
|
55098b25a3 | ||
|
|
793af1a1f1 | ||
|
|
689885ffa4 | ||
|
|
a07316da6e | ||
|
|
eb1732b7a1 | ||
|
|
e1049fa78c |
5
.flake8
Normal file
@ -0,0 +1,5 @@
|
||||
[flake8]
|
||||
max-line-length = 88
|
||||
select = C,E,F,W,B,B9
|
||||
ignore = E203, E501, W503
|
||||
exclude = __init__.py
|
||||
6
.github/ISSUE_TEMPLATE/config.yml
vendored
@ -4,10 +4,10 @@ contact_links:
|
||||
about: Please report security vulnerabilities to security@tiangolo.com
|
||||
- name: Question or Problem
|
||||
about: Ask a question or ask about a problem in GitHub Discussions.
|
||||
url: https://github.com/fastapi/sqlmodel/discussions/categories/questions
|
||||
url: https://github.com/tiangolo/sqlmodel/discussions/categories/questions
|
||||
- name: Feature Request
|
||||
about: To suggest an idea or ask about a feature, please start with a question saying what you would like to achieve. There might be a way to do it already.
|
||||
url: https://github.com/fastapi/sqlmodel/discussions/categories/questions
|
||||
url: https://github.com/tiangolo/sqlmodel/discussions/categories/questions
|
||||
- name: Show and tell
|
||||
about: Show what you built with SQLModel or to be used with SQLModel.
|
||||
url: https://github.com/fastapi/sqlmodel/discussions/categories/show-and-tell
|
||||
url: https://github.com/tiangolo/sqlmodel/discussions/categories/show-and-tell
|
||||
|
||||
2
.github/ISSUE_TEMPLATE/privileged.yml
vendored
@ -6,7 +6,7 @@ body:
|
||||
value: |
|
||||
Thanks for your interest in SQLModel! 🚀
|
||||
|
||||
If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/fastapi/sqlmodel/discussions/categories/questions) instead.
|
||||
If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/tiangolo/sqlmodel/discussions/categories/questions) instead.
|
||||
- type: checkboxes
|
||||
id: privileged
|
||||
attributes:
|
||||
|
||||
7
.github/actions/comment-docs-preview-in-pr/Dockerfile
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
FROM python:3.7
|
||||
|
||||
RUN pip install httpx "pydantic==1.5.1" pygithub
|
||||
|
||||
COPY ./app /app
|
||||
|
||||
CMD ["python", "/app/main.py"]
|
||||
13
.github/actions/comment-docs-preview-in-pr/action.yml
vendored
Normal file
@ -0,0 +1,13 @@
|
||||
name: Comment Docs Preview in PR
|
||||
description: Comment with the docs URL preview in the PR
|
||||
author: Sebastián Ramírez <tiangolo@gmail.com>
|
||||
inputs:
|
||||
token:
|
||||
description: Token for the repo. Can be passed in using {{ secrets.GITHUB_TOKEN }}
|
||||
required: true
|
||||
deploy_url:
|
||||
description: The deployment URL to comment in the PR
|
||||
required: true
|
||||
runs:
|
||||
using: docker
|
||||
image: Dockerfile
|
||||
68
.github/actions/comment-docs-preview-in-pr/app/main.py
vendored
Normal file
@ -0,0 +1,68 @@
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
from github import Github
|
||||
from github.PullRequest import PullRequest
|
||||
from pydantic import BaseModel, BaseSettings, SecretStr, ValidationError
|
||||
|
||||
github_api = "https://api.github.com"
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
github_repository: str
|
||||
github_event_path: Path
|
||||
github_event_name: Optional[str] = None
|
||||
input_token: SecretStr
|
||||
input_deploy_url: str
|
||||
|
||||
|
||||
class PartialGithubEventHeadCommit(BaseModel):
|
||||
id: str
|
||||
|
||||
|
||||
class PartialGithubEventWorkflowRun(BaseModel):
|
||||
head_commit: PartialGithubEventHeadCommit
|
||||
|
||||
|
||||
class PartialGithubEvent(BaseModel):
|
||||
workflow_run: PartialGithubEventWorkflowRun
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
settings = Settings()
|
||||
logging.info(f"Using config: {settings.json()}")
|
||||
g = Github(settings.input_token.get_secret_value())
|
||||
repo = g.get_repo(settings.github_repository)
|
||||
try:
|
||||
event = PartialGithubEvent.parse_file(settings.github_event_path)
|
||||
except ValidationError as e:
|
||||
logging.error(f"Error parsing event file: {e.errors()}")
|
||||
sys.exit(0)
|
||||
use_pr: Optional[PullRequest] = None
|
||||
for pr in repo.get_pulls():
|
||||
if pr.head.sha == event.workflow_run.head_commit.id:
|
||||
use_pr = pr
|
||||
break
|
||||
if not use_pr:
|
||||
logging.error(f"No PR found for hash: {event.workflow_run.head_commit.id}")
|
||||
sys.exit(0)
|
||||
github_headers = {
|
||||
"Authorization": f"token {settings.input_token.get_secret_value()}"
|
||||
}
|
||||
url = f"{github_api}/repos/{settings.github_repository}/issues/{use_pr.number}/comments"
|
||||
logging.info(f"Using comments URL: {url}")
|
||||
response = httpx.post(
|
||||
url,
|
||||
headers=github_headers,
|
||||
json={
|
||||
"body": f"📝 Docs preview for commit {use_pr.head.sha} at: {settings.input_deploy_url}"
|
||||
},
|
||||
)
|
||||
if not (200 <= response.status_code <= 300):
|
||||
logging.error(f"Error posting comment: {response.text}")
|
||||
sys.exit(1)
|
||||
logging.info("Finished")
|
||||
24
.github/labeler.yml
vendored
@ -1,24 +0,0 @@
|
||||
docs:
|
||||
- all:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- docs/**
|
||||
- docs_src/**
|
||||
- all-globs-to-all-files:
|
||||
- '!sqlmodel/**'
|
||||
- '!pyproject.toml'
|
||||
|
||||
internal:
|
||||
- all:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- .github/**
|
||||
- scripts/**
|
||||
- .gitignore
|
||||
- .pre-commit-config.yaml
|
||||
- pdm_build.py
|
||||
- requirements*.txt
|
||||
- all-globs-to-all-files:
|
||||
- '!docs/**'
|
||||
- '!sqlmodel/**'
|
||||
- '!pyproject.toml'
|
||||
18
.github/workflows/add-to-project.yml
vendored
@ -1,18 +0,0 @@
|
||||
name: Add to Project
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
issues:
|
||||
types:
|
||||
- opened
|
||||
- reopened
|
||||
|
||||
jobs:
|
||||
add-to-project:
|
||||
name: Add to project
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/add-to-project@v1.0.2
|
||||
with:
|
||||
project-url: https://github.com/orgs/fastapi/projects/2
|
||||
github-token: ${{ secrets.PROJECTS_TOKEN }}
|
||||
58
.github/workflows/build-docs.yml
vendored
@ -7,11 +7,6 @@ on:
|
||||
types:
|
||||
- opened
|
||||
- synchronize
|
||||
|
||||
env:
|
||||
UV_SYSTEM_PYTHON: 1
|
||||
|
||||
|
||||
jobs:
|
||||
changes:
|
||||
runs-on: ubuntu-latest
|
||||
@ -24,7 +19,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
# For pull requests it's not necessary to checkout the code but for the main branch it is
|
||||
- uses: dorny/paths-filter@v3
|
||||
- uses: dorny/paths-filter@v2
|
||||
id: filter
|
||||
with:
|
||||
filters: |
|
||||
@ -32,15 +27,9 @@ jobs:
|
||||
- README.md
|
||||
- docs/**
|
||||
- docs_src/**
|
||||
- requirements-docs.txt
|
||||
- requirements-docs-insiders.txt
|
||||
- pyproject.toml
|
||||
- mkdocs.yml
|
||||
- mkdocs.insiders.yml
|
||||
- mkdocs.maybe-insiders.yml
|
||||
- mkdocs.no-insiders.yml
|
||||
- .github/workflows/build-docs.yml
|
||||
- .github/workflows/deploy-docs.yml
|
||||
|
||||
build-docs:
|
||||
needs:
|
||||
@ -54,37 +43,42 @@ jobs:
|
||||
run: echo "$GITHUB_CONTEXT"
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: "3.11"
|
||||
- name: Setup uv
|
||||
uses: astral-sh/setup-uv@v3
|
||||
- uses: actions/cache@v3
|
||||
id: cache
|
||||
with:
|
||||
version: "0.4.15"
|
||||
enable-cache: true
|
||||
cache-dependency-glob: |
|
||||
requirements**.txt
|
||||
pyproject.toml
|
||||
- name: Install docs extras
|
||||
run: uv pip install -r requirements-docs.txt
|
||||
path: ${{ env.pythonLocation }}
|
||||
key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-v01
|
||||
- name: Install Poetry
|
||||
if: steps.cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install "poetry"
|
||||
python -m poetry self add poetry-version-plugin
|
||||
- name: Configure poetry
|
||||
run: python -m poetry config virtualenvs.create false
|
||||
- name: Install Dependencies
|
||||
if: steps.cache.outputs.cache-hit != 'true'
|
||||
run: python -m poetry install
|
||||
- name: Install Material for MkDocs Insiders
|
||||
if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' )
|
||||
run: uv pip install -r requirements-docs-insiders.txt
|
||||
env:
|
||||
TOKEN: ${{ secrets.SQLMODEL_MKDOCS_MATERIAL_INSIDERS }}
|
||||
- uses: actions/cache@v4
|
||||
if: ( github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false ) && steps.cache.outputs.cache-hit != 'true'
|
||||
run: python -m poetry run pip install git+https://${{ secrets.SQLMODEL_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git
|
||||
- uses: actions/cache@v3
|
||||
with:
|
||||
key: mkdocs-cards-${{ github.ref }}
|
||||
path: .cache
|
||||
- name: Verify README
|
||||
run: python ./scripts/docs.py verify-readme
|
||||
- name: Build Docs
|
||||
run: python ./scripts/docs.py build
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork == true
|
||||
run: python -m poetry run mkdocs build
|
||||
- name: Build Docs with Insiders
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.fork == false
|
||||
run: python -m poetry run mkdocs build --config-file mkdocs.insiders.yml
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: docs-site
|
||||
path: ./site/**
|
||||
include-hidden-files: true
|
||||
|
||||
# https://github.com/marketplace/actions/alls-green#why
|
||||
docs-all-green: # This job does nothing and is only used for the branch protection
|
||||
|
||||
68
.github/workflows/deploy-docs.yml
vendored
@ -6,15 +6,6 @@ on:
|
||||
types:
|
||||
- completed
|
||||
|
||||
permissions:
|
||||
deployments: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
statuses: write
|
||||
|
||||
env:
|
||||
UV_SYSTEM_PYTHON: 1
|
||||
|
||||
jobs:
|
||||
deploy-docs:
|
||||
runs-on: ubuntu-latest
|
||||
@ -24,55 +15,34 @@ jobs:
|
||||
GITHUB_CONTEXT: ${{ toJson(github) }}
|
||||
run: echo "$GITHUB_CONTEXT"
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.11"
|
||||
- name: Setup uv
|
||||
uses: astral-sh/setup-uv@v3
|
||||
with:
|
||||
version: "0.4.15"
|
||||
enable-cache: true
|
||||
cache-dependency-glob: |
|
||||
requirements**.txt
|
||||
pyproject.toml
|
||||
- name: Install GitHub Actions dependencies
|
||||
run: uv pip install -r requirements-github-actions.txt
|
||||
- name: Deploy Docs Status Pending
|
||||
run: python ./scripts/deploy_docs_status.py
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
COMMIT_SHA: ${{ github.event.workflow_run.head_sha }}
|
||||
RUN_ID: ${{ github.run_id }}
|
||||
|
||||
- name: Clean site
|
||||
run: |
|
||||
rm -rf ./site
|
||||
mkdir ./site
|
||||
- uses: actions/download-artifact@v4
|
||||
- name: Download Artifact Docs
|
||||
id: download
|
||||
uses: dawidd6/action-download-artifact@v2.28.0
|
||||
with:
|
||||
if_no_artifact_found: ignore
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
workflow: build-docs.yml
|
||||
run_id: ${{ github.event.workflow_run.id }}
|
||||
name: docs-site
|
||||
path: ./site/
|
||||
pattern: docs-site
|
||||
merge-multiple: true
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
run-id: ${{ github.event.workflow_run.id }}
|
||||
- name: Deploy to Cloudflare Pages
|
||||
# hashFiles returns an empty string if there are no files
|
||||
if: hashFiles('./site/*')
|
||||
if: steps.download.outputs.found_artifact == 'true'
|
||||
id: deploy
|
||||
env:
|
||||
PROJECT_NAME: sqlmodel
|
||||
BRANCH: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'main' && 'main' ) || ( github.event.workflow_run.head_sha ) }}
|
||||
uses: cloudflare/wrangler-action@v3
|
||||
uses: cloudflare/pages-action@v1
|
||||
with:
|
||||
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
command: pages deploy ./site --project-name=${{ env.PROJECT_NAME }} --branch=${{ env.BRANCH }}
|
||||
projectName: sqlmodel
|
||||
directory: './site'
|
||||
gitHubToken: ${{ secrets.GITHUB_TOKEN }}
|
||||
branch: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'main' && 'main' ) || ( github.event.workflow_run.head_sha ) }}
|
||||
- name: Comment Deploy
|
||||
run: python ./scripts/deploy_docs_status.py
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
DEPLOY_URL: ${{ steps.deploy.outputs.deployment-url }}
|
||||
COMMIT_SHA: ${{ github.event.workflow_run.head_sha }}
|
||||
RUN_ID: ${{ github.run_id }}
|
||||
IS_DONE: "true"
|
||||
if: steps.deploy.outputs.url != ''
|
||||
uses: ./.github/actions/comment-docs-preview-in-pr
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
deploy_url: "${{ steps.deploy.outputs.url }}"
|
||||
|
||||
21
.github/workflows/issue-manager.yml
vendored
@ -2,7 +2,7 @@ name: Issue Manager
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "13 18 * * *"
|
||||
- cron: "0 0 * * *"
|
||||
issue_comment:
|
||||
types:
|
||||
- created
|
||||
@ -14,20 +14,11 @@ on:
|
||||
- labeled
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
issue-manager:
|
||||
if: github.repository_owner == 'fastapi'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Dump GitHub context
|
||||
env:
|
||||
GITHUB_CONTEXT: ${{ toJson(github) }}
|
||||
run: echo "$GITHUB_CONTEXT"
|
||||
- uses: tiangolo/issue-manager@0.5.1
|
||||
- uses: tiangolo/issue-manager@0.4.0
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
config: >
|
||||
@ -35,13 +26,5 @@ jobs:
|
||||
"answered": {
|
||||
"delay": 864000,
|
||||
"message": "Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs."
|
||||
},
|
||||
"waiting": {
|
||||
"delay": 2628000,
|
||||
"message": "As this PR has been waiting for the original user for a while but seems to be inactive, it's now going to be closed. But if there's anyone interested, feel free to create a new PR."
|
||||
},
|
||||
"invalid": {
|
||||
"delay": 0,
|
||||
"message": "This was marked as invalid and will be closed now. If this is an error, please provide additional details."
|
||||
}
|
||||
}
|
||||
|
||||
33
.github/workflows/labeler.yml
vendored
@ -1,33 +0,0 @@
|
||||
name: Labels
|
||||
on:
|
||||
pull_request_target:
|
||||
types:
|
||||
- opened
|
||||
- synchronize
|
||||
- reopened
|
||||
# For label-checker
|
||||
- labeled
|
||||
- unlabeled
|
||||
|
||||
jobs:
|
||||
labeler:
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/labeler@v5
|
||||
if: ${{ github.event.action != 'labeled' && github.event.action != 'unlabeled' }}
|
||||
- run: echo "Done adding labels"
|
||||
# Run this after labeler applied labels
|
||||
check-labels:
|
||||
needs:
|
||||
- labeler
|
||||
permissions:
|
||||
pull-requests: read
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: docker://agilepathway/pull-request-label-checker:latest
|
||||
with:
|
||||
one_of: breaking,security,feature,bug,refactor,upgrade,docs,lang-all,internal
|
||||
repo_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
6
.github/workflows/latest-changes.yml
vendored
@ -30,11 +30,9 @@ jobs:
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }}
|
||||
with:
|
||||
limit-access-to-actor: true
|
||||
- uses: tiangolo/latest-changes@0.3.1
|
||||
- uses: docker://tiangolo/latest-changes:0.0.3
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
latest_changes_file: docs/release-notes.md
|
||||
latest_changes_header: '## Latest Changes'
|
||||
end_regex: '^## '
|
||||
latest_changes_header: '## Latest Changes\n\n'
|
||||
debug_logs: true
|
||||
label_header_prefix: '### '
|
||||
|
||||
45
.github/workflows/publish.yml
vendored
@ -14,24 +14,37 @@ on:
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
package:
|
||||
- sqlmodel
|
||||
- sqlmodel-slim
|
||||
permissions:
|
||||
id-token: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: "3.11"
|
||||
- name: Install build dependencies
|
||||
run: pip install build
|
||||
- name: Build distribution
|
||||
env:
|
||||
TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }}
|
||||
run: python -m build
|
||||
python-version: "3.7"
|
||||
# Allow debugging with tmate
|
||||
- name: Setup tmate session
|
||||
uses: mxschmitt/action-tmate@v3
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }}
|
||||
with:
|
||||
limit-access-to-actor: true
|
||||
- uses: actions/cache@v3
|
||||
id: cache
|
||||
with:
|
||||
path: ${{ env.pythonLocation }}
|
||||
key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-root-v2
|
||||
- name: Install poetry
|
||||
if: steps.cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install "poetry"
|
||||
python -m poetry self add poetry-version-plugin
|
||||
- name: Configure poetry
|
||||
run: python -m poetry config virtualenvs.create false
|
||||
- name: Install Dependencies
|
||||
if: steps.cache.outputs.cache-hit != 'true'
|
||||
run: python -m poetry install
|
||||
- name: Publish
|
||||
uses: pypa/gh-action-pypi-publish@v1.9.0
|
||||
env:
|
||||
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
|
||||
run: |
|
||||
python -m poetry config pypi-token.pypi $PYPI_TOKEN
|
||||
bash scripts/publish.sh
|
||||
|
||||
30
.github/workflows/smokeshow.yml
vendored
@ -8,34 +8,24 @@ on:
|
||||
permissions:
|
||||
statuses: write
|
||||
|
||||
env:
|
||||
UV_SYSTEM_PYTHON: 1
|
||||
|
||||
jobs:
|
||||
smokeshow:
|
||||
if: ${{ github.event.workflow_run.conclusion == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
- uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: '3.9'
|
||||
- name: Setup uv
|
||||
uses: astral-sh/setup-uv@v3
|
||||
|
||||
- run: pip install smokeshow
|
||||
|
||||
- uses: dawidd6/action-download-artifact@v2.28.0
|
||||
with:
|
||||
version: "0.4.15"
|
||||
enable-cache: true
|
||||
cache-dependency-glob: |
|
||||
requirements**.txt
|
||||
pyproject.toml
|
||||
- run: uv pip install -r requirements-github-actions.txt
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: coverage-html
|
||||
path: htmlcov
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
run-id: ${{ github.event.workflow_run.id }}
|
||||
- run: smokeshow upload htmlcov
|
||||
workflow: test.yml
|
||||
commit: ${{ github.event.workflow_run.head_sha }}
|
||||
|
||||
- run: smokeshow upload coverage-html
|
||||
env:
|
||||
SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage}
|
||||
SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 95
|
||||
|
||||
65
.github/workflows/test-redistribute.yml
vendored
@ -1,65 +0,0 @@
|
||||
name: Test Redistribute
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
types:
|
||||
- opened
|
||||
- synchronize
|
||||
|
||||
jobs:
|
||||
test-redistribute:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
package:
|
||||
- sqlmodel
|
||||
- sqlmodel-slim
|
||||
steps:
|
||||
- name: Dump GitHub context
|
||||
env:
|
||||
GITHUB_CONTEXT: ${{ toJson(github) }}
|
||||
run: echo "$GITHUB_CONTEXT"
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.10"
|
||||
- name: Install build dependencies
|
||||
run: pip install build
|
||||
- name: Build source distribution
|
||||
env:
|
||||
TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }}
|
||||
run: python -m build --sdist
|
||||
- name: Decompress source distribution
|
||||
run: |
|
||||
cd dist
|
||||
tar xvf sqlmodel*.tar.gz
|
||||
- name: Install test dependencies
|
||||
run: |
|
||||
cd dist/sqlmodel*/
|
||||
pip install -r requirements-tests.txt
|
||||
env:
|
||||
TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }}
|
||||
- name: Run source distribution tests
|
||||
run: |
|
||||
cd dist/sqlmodel*/
|
||||
bash scripts/test.sh
|
||||
- name: Build wheel distribution
|
||||
run: |
|
||||
cd dist
|
||||
pip wheel --no-deps sqlmodel*.tar.gz
|
||||
|
||||
# https://github.com/marketplace/actions/alls-green#why
|
||||
test-redistribute-alls-green: # This job does nothing and is only used for the branch protection
|
||||
if: always()
|
||||
needs:
|
||||
- test-redistribute
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Decide whether the needed jobs succeeded or failed
|
||||
uses: re-actors/alls-green@release/v1
|
||||
with:
|
||||
jobs: ${{ toJSON(needs) }}
|
||||
89
.github/workflows/test.yml
vendored
@ -14,12 +14,6 @@ on:
|
||||
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
|
||||
required: false
|
||||
default: 'false'
|
||||
schedule:
|
||||
# cron every week on monday
|
||||
- cron: "0 0 * * 1"
|
||||
|
||||
env:
|
||||
UV_SYSTEM_PYTHON: 1
|
||||
|
||||
jobs:
|
||||
test:
|
||||
@ -31,92 +25,79 @@ jobs:
|
||||
- "3.8"
|
||||
- "3.9"
|
||||
- "3.10"
|
||||
- "3.11"
|
||||
- "3.12"
|
||||
pydantic-version:
|
||||
- pydantic-v1
|
||||
- pydantic-v2
|
||||
fail-fast: false
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
- name: Setup uv
|
||||
uses: astral-sh/setup-uv@v3
|
||||
with:
|
||||
version: "0.4.15"
|
||||
enable-cache: true
|
||||
cache-dependency-glob: |
|
||||
requirements**.txt
|
||||
pyproject.toml
|
||||
# Allow debugging with tmate
|
||||
- name: Setup tmate session
|
||||
uses: mxschmitt/action-tmate@v3
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }}
|
||||
with:
|
||||
limit-access-to-actor: true
|
||||
- uses: actions/cache@v3
|
||||
id: cache
|
||||
with:
|
||||
path: ${{ env.pythonLocation }}
|
||||
key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-root-v2
|
||||
- name: Install poetry
|
||||
if: steps.cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install "poetry"
|
||||
python -m poetry self add poetry-version-plugin
|
||||
- name: Configure poetry
|
||||
run: python -m poetry config virtualenvs.create false
|
||||
- name: Install Dependencies
|
||||
run: uv pip install -r requirements-tests.txt
|
||||
- name: Install Pydantic v1
|
||||
if: matrix.pydantic-version == 'pydantic-v1'
|
||||
run: uv pip install --upgrade "pydantic>=1.10.0,<2.0.0"
|
||||
- name: Install Pydantic v2
|
||||
if: matrix.pydantic-version == 'pydantic-v2'
|
||||
run: uv pip install --upgrade "pydantic>=2.0.2,<3.0.0" "typing-extensions==4.6.1"
|
||||
if: steps.cache.outputs.cache-hit != 'true'
|
||||
run: python -m poetry install
|
||||
- name: Lint
|
||||
# Do not run on Python 3.7 as mypy behaves differently
|
||||
if: matrix.python-version != '3.7' && matrix.pydantic-version == 'pydantic-v2'
|
||||
run: bash scripts/lint.sh
|
||||
run: python -m poetry run bash scripts/lint.sh
|
||||
- run: mkdir coverage
|
||||
- name: Test
|
||||
run: bash scripts/test.sh
|
||||
run: python -m poetry run bash scripts/test.sh
|
||||
env:
|
||||
COVERAGE_FILE: coverage/.coverage.${{ runner.os }}-py${{ matrix.python-version }}-${{ matrix.pydantic-version }}
|
||||
COVERAGE_FILE: coverage/.coverage.${{ runner.os }}-py${{ matrix.python-version }}
|
||||
CONTEXT: ${{ runner.os }}-py${{ matrix.python-version }}
|
||||
- name: Store coverage files
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: coverage-${{ matrix.python-version }}-${{ matrix.pydantic-version }}
|
||||
name: coverage
|
||||
path: coverage
|
||||
include-hidden-files: true
|
||||
|
||||
coverage-combine:
|
||||
needs:
|
||||
- test
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-python@v5
|
||||
|
||||
- uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: '3.12'
|
||||
- name: Setup uv
|
||||
uses: astral-sh/setup-uv@v3
|
||||
with:
|
||||
version: "0.4.15"
|
||||
enable-cache: true
|
||||
cache-dependency-glob: |
|
||||
requirements**.txt
|
||||
pyproject.toml
|
||||
python-version: '3.8'
|
||||
|
||||
- name: Get coverage files
|
||||
uses: actions/download-artifact@v4
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
pattern: coverage-*
|
||||
name: coverage
|
||||
path: coverage
|
||||
merge-multiple: true
|
||||
- name: Install Dependencies
|
||||
run: uv pip install -r requirements-tests.txt
|
||||
|
||||
- run: pip install coverage[toml]
|
||||
|
||||
- run: ls -la coverage
|
||||
- run: coverage combine coverage
|
||||
- run: coverage report
|
||||
- run: coverage html --title "Coverage for ${{ github.sha }}"
|
||||
- run: coverage html --show-contexts --title "Coverage for ${{ github.sha }}"
|
||||
|
||||
- name: Store coverage HTML
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: coverage-html
|
||||
path: htmlcov
|
||||
include-hidden-files: true
|
||||
|
||||
# https://github.com/marketplace/actions/alls-green#why
|
||||
alls-green: # This job does nothing and is only used for the branch protection
|
||||
|
||||
4
.gitignore
vendored
@ -1,4 +1,5 @@
|
||||
*.pyc
|
||||
env*
|
||||
.mypy_cache
|
||||
.vscode
|
||||
.idea
|
||||
@ -6,9 +7,8 @@ poetry.lock
|
||||
dist
|
||||
htmlcov
|
||||
*.egg-info
|
||||
.coverage*
|
||||
.coverage
|
||||
coverage.xml
|
||||
site
|
||||
*.db
|
||||
.cache
|
||||
.venv*
|
||||
|
||||
@ -4,7 +4,7 @@ default_language_version:
|
||||
python: python3.10
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.6.0
|
||||
rev: v4.5.0
|
||||
hooks:
|
||||
- id: check-added-large-files
|
||||
- id: check-toml
|
||||
@ -13,8 +13,8 @@ repos:
|
||||
- --unsafe
|
||||
- id: end-of-file-fixer
|
||||
- id: trailing-whitespace
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.6.5
|
||||
- repo: https://github.com/charliermarsh/ruff-pre-commit
|
||||
rev: v0.1.2
|
||||
hooks:
|
||||
- id: ruff
|
||||
args:
|
||||
|
||||
@ -12,7 +12,7 @@ authors:
|
||||
family-names: Ramírez
|
||||
email: tiangolo@gmail.com
|
||||
identifiers:
|
||||
repository-code: 'https://github.com/fastapi/sqlmodel'
|
||||
repository-code: 'https://github.com/tiangolo/sqlmodel'
|
||||
url: 'https://sqlmodel.tiangolo.com'
|
||||
abstract: >-
|
||||
SQLModel, SQL databases in Python, designed for
|
||||
|
||||
31
README.md
@ -1,19 +1,18 @@
|
||||
<p align="center">
|
||||
<a href="https://sqlmodel.tiangolo.com"><img src="https://sqlmodel.tiangolo.com/img/logo-margin/logo-margin-vector.svg#only-light" alt="SQLModel"></a>
|
||||
|
||||
<a href="https://sqlmodel.tiangolo.com"><img src="https://sqlmodel.tiangolo.com/img/logo-margin/logo-margin-vector.svg" alt="SQLModel"></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
<em>SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness.</em>
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://github.com/fastapi/sqlmodel/actions?query=workflow%3ATest" target="_blank">
|
||||
<img src="https://github.com/fastapi/sqlmodel/workflows/Test/badge.svg" alt="Test">
|
||||
<a href="https://github.com/tiangolo/sqlmodel/actions?query=workflow%3ATest" target="_blank">
|
||||
<img src="https://github.com/tiangolo/sqlmodel/workflows/Test/badge.svg" alt="Test">
|
||||
</a>
|
||||
<a href="https://github.com/fastapi/sqlmodel/actions?query=workflow%3APublish" target="_blank">
|
||||
<img src="https://github.com/fastapi/sqlmodel/workflows/Publish/badge.svg" alt="Publish">
|
||||
<a href="https://github.com/tiangolo/sqlmodel/actions?query=workflow%3APublish" target="_blank">
|
||||
<img src="https://github.com/tiangolo/sqlmodel/workflows/Publish/badge.svg" alt="Publish">
|
||||
</a>
|
||||
<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/sqlmodel" target="_blank">
|
||||
<img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/sqlmodel.svg" alt="Coverage">
|
||||
<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/sqlmodel" target="_blank">
|
||||
<img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/sqlmodel.svg" alt="Coverage">
|
||||
<a href="https://pypi.org/project/sqlmodel" target="_blank">
|
||||
<img src="https://img.shields.io/pypi/v/sqlmodel?color=%2334D058&label=pypi%20package" alt="Package version">
|
||||
</a>
|
||||
@ -23,7 +22,7 @@
|
||||
|
||||
**Documentation**: <a href="https://sqlmodel.tiangolo.com" target="_blank">https://sqlmodel.tiangolo.com</a>
|
||||
|
||||
**Source Code**: <a href="https://github.com/fastapi/sqlmodel" target="_blank">https://github.com/fastapi/sqlmodel</a>
|
||||
**Source Code**: <a href="https://github.com/tiangolo/sqlmodel" target="_blank">https://github.com/tiangolo/sqlmodel</a>
|
||||
|
||||
---
|
||||
|
||||
@ -39,14 +38,6 @@ The key features are:
|
||||
* **Extensible**: You have all the power of SQLAlchemy and Pydantic underneath.
|
||||
* **Short**: Minimize code duplication. A single type annotation does a lot of work. No need to duplicate models in SQLAlchemy and Pydantic.
|
||||
|
||||
## Sponsors
|
||||
|
||||
<!-- sponsors -->
|
||||
|
||||
<a href="https://www.govcert.lu" target="_blank" title="This project is being supported by GOVCERT.LU"><img src="https://sqlmodel.tiangolo.com/img/sponsors/govcert.png"></a>
|
||||
|
||||
<!-- /sponsors -->
|
||||
|
||||
## SQL Databases in FastAPI
|
||||
|
||||
<a href="https://fastapi.tiangolo.com" target="_blank"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" style="width: 20%;"></a>
|
||||
@ -65,8 +56,6 @@ As **SQLModel** is based on **Pydantic** and **SQLAlchemy**, it requires them. T
|
||||
|
||||
## Installation
|
||||
|
||||
Make sure you create a <a href="https://sqlmodel.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a>, activate it, and then install SQLModel, for example with:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
@ -79,7 +68,7 @@ Successfully installed sqlmodel
|
||||
|
||||
## Example
|
||||
|
||||
For an introduction to databases, SQL, and everything else, see the <a href="https://sqlmodel.tiangolo.com/databases/" target="_blank">SQLModel documentation</a>.
|
||||
For an introduction to databases, SQL, and everything else, see the <a href="https://sqlmodel.tiangolo.com" target="_blank">SQLModel documentation</a>.
|
||||
|
||||
Here's a quick example. ✨
|
||||
|
||||
@ -222,4 +211,4 @@ And at the same time, ✨ it is also a **Pydantic** model ✨. You can use inher
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the terms of the [MIT license](https://github.com/fastapi/sqlmodel/blob/main/LICENSE).
|
||||
This project is licensed under the terms of the [MIT license](https://github.com/tiangolo/sqlmodel/blob/main/LICENSE).
|
||||
|
||||
@ -1,4 +0,0 @@
|
||||
members:
|
||||
- login: tiangolo
|
||||
- login: estebanx64
|
||||
- login: alejsdev
|
||||
@ -1,6 +0,0 @@
|
||||
gold: []
|
||||
silver:
|
||||
- url: https://www.govcert.lu
|
||||
title: This project is being supported by GOVCERT.LU
|
||||
img: https://sqlmodel.tiangolo.com/img/sponsors/govcert.png
|
||||
bronze: []
|
||||
@ -1,3 +0,0 @@
|
||||
# About
|
||||
|
||||
About **SQLModel**, its design, inspiration, and more. 🤓
|
||||
@ -19,59 +19,36 @@ In most cases this would probably not be a problem, for example measuring views
|
||||
|
||||
## Decimal Types
|
||||
|
||||
Pydantic has special support for <a href="https://docs.pydantic.dev/latest/api/standard_library_types/#decimaldecimal" class="external-link" target="_blank">`Decimal` types</a>.
|
||||
Pydantic has special support for `Decimal` types using the <a href="https://pydantic-docs.helpmanual.io/usage/types/#arguments-to-condecimal" class="external-link" target="_blank">`condecimal()` special function</a>.
|
||||
|
||||
When you use `Decimal` you can specify the number of digits and decimal places to support in the `Field()` function. They will be validated by Pydantic (for example when using FastAPI) and the same information will also be used for the database columns.
|
||||
!!! tip
|
||||
Pydantic 1.9, that will be released soon, has improved support for `Decimal` types, without needing to use the `condecimal()` function.
|
||||
|
||||
/// info
|
||||
But meanwhile, you can already use this feature with `condecimal()` in **SQLModel** it as it's explained here.
|
||||
|
||||
For the database, **SQLModel** will use <a href="https://docs.sqlalchemy.org/en/20/core/type_basics.html#sqlalchemy.types.DECIMAL" class="external-link" target="_blank">SQLAlchemy's `DECIMAL` type</a>.
|
||||
When you use `condecimal()` you can specify the number of digits and decimal places to support. They will be validated by Pydantic (for example when using FastAPI) and the same information will also be used for the database columns.
|
||||
|
||||
///
|
||||
!!! info
|
||||
For the database, **SQLModel** will use <a href="https://docs.sqlalchemy.org/en/14/core/type_basics.html#sqlalchemy.types.DECIMAL" class="external-link" target="_blank">SQLAlchemy's `DECIMAL` type</a>.
|
||||
|
||||
## Decimals in SQLModel
|
||||
|
||||
Let's say that each hero in the database will have an amount of money. We could make that field a `Decimal` type using the `condecimal()` function:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```python hl_lines="11"
|
||||
{!./docs_src/advanced/decimal/tutorial001_py310.py[ln:1-11]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```python hl_lines="12"
|
||||
```{.python .annotate hl_lines="12" }
|
||||
{!./docs_src/advanced/decimal/tutorial001.py[ln:1-12]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/advanced/decimal/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/advanced/decimal/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Here we are saying that `money` can have at most `5` digits with `max_digits`, **this includes the integers** (to the left of the decimal dot) **and the decimals** (to the right of the decimal dot).
|
||||
|
||||
@ -89,36 +66,19 @@ We are also saying that the number of decimal places (to the right of the decima
|
||||
🚫 But these are all invalid numbers for that `money` field:
|
||||
|
||||
* `1.2345`
|
||||
* This number has more than 3 decimal places.
|
||||
* This number has more than 3 decimal places.
|
||||
* `123.234`
|
||||
* This number has more than 5 digits in total (integer and decimal part).
|
||||
* This number has more than 5 digits in total (integer and decimal part).
|
||||
* `123`
|
||||
* Even though this number doesn't have any decimals, we still have 3 places saved for them, which means that we can **only use 2 places** for the **integer part**, and this number has 3 integer digits. So, the allowed number of integer digits is `max_digits` - `decimal_places` = 2.
|
||||
* Even though this number doesn't have any decimals, we still have 3 places saved for them, which means that we can **only use 2 places** for the **integer part**, and this number has 3 integer digits. So, the allowed number of integer digits is `max_digits` - `decimal_places` = 2.
|
||||
|
||||
/// tip
|
||||
|
||||
Make sure you adjust the number of digits and decimal places for your own needs, in your own application. 🤓
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Make sure you adjust the number of digits and decimal places for your own needs, in your own application. 🤓
|
||||
|
||||
## Create models with Decimals
|
||||
|
||||
When creating new models you can actually pass normal (`float`) numbers, Pydantic will automatically convert them to `Decimal` types, and **SQLModel** will store them as `Decimal` types in the database (using SQLAlchemy).
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="4-6"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/advanced/decimal/tutorial001_py310.py[ln:24-34]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="4-6"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -127,46 +87,19 @@ When creating new models you can actually pass normal (`float`) numbers, Pydanti
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/advanced/decimal/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/advanced/decimal/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Select Decimal data
|
||||
|
||||
Then, when working with Decimal types, you can confirm that they indeed avoid those rounding errors from floats:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="15-16"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/advanced/decimal/tutorial001_py310.py[ln:37-50]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="15-16"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -175,27 +108,14 @@ Then, when working with Decimal types, you can confirm that they indeed avoid th
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/advanced/decimal/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/advanced/decimal/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Review the results
|
||||
|
||||
@ -222,10 +142,7 @@ Total money: 3.300
|
||||
|
||||
</div>
|
||||
|
||||
/// warning
|
||||
!!! warning
|
||||
Although Decimal types are supported and used in the Python side, not all databases support it. In particular, SQLite doesn't support decimals, so it will convert them to the same floating `NUMERIC` type it supports.
|
||||
|
||||
Although Decimal types are supported and used in the Python side, not all databases support it. In particular, SQLite doesn't support decimals, so it will convert them to the same floating `NUMERIC` type it supports.
|
||||
|
||||
But decimals are supported by most of the other SQL databases. 🎉
|
||||
|
||||
///
|
||||
But decimals are supported by most of the other SQL databases. 🎉
|
||||
|
||||
@ -1,178 +0,0 @@
|
||||
# UUID (Universally Unique Identifiers)
|
||||
|
||||
We have discussed some data types like `str`, `int`, etc.
|
||||
|
||||
There's another data type called `UUID` (Universally Unique Identifier).
|
||||
|
||||
You might have seen **UUIDs**, for example in URLs. They look something like this:
|
||||
|
||||
```
|
||||
4ff2dab7-bffe-414d-88a5-1826b9fea8df
|
||||
```
|
||||
|
||||
UUIDs can be particularly useful as an alternative to auto-incrementing integers for **primary keys**.
|
||||
|
||||
/// info
|
||||
|
||||
Official support for UUIDs was added in SQLModel version `0.0.20`.
|
||||
|
||||
///
|
||||
|
||||
## About UUIDs
|
||||
|
||||
UUIDs are numbers with 128 bits, that is, 16 bytes.
|
||||
|
||||
They are normally seen as 32 <abbr title="numbers in base 16 (instead of base 10), using letters from A to F to represent the numbers from 10 to 15">hexadecimal</abbr> characters separated by dashes.
|
||||
|
||||
There are several versions of UUID, some versions include the current time in the bytes, but **UUIDs version 4** are mainly random, the way they are generated makes them virtually **unique**.
|
||||
|
||||
### Distributed UUIDs
|
||||
|
||||
You could generate one UUID in one computer, and someone else could generate another UUID in another computer, and it would be almost **impossible** for both UUIDs to be the **same**.
|
||||
|
||||
This means that you don't have to wait for the DB to generate the ID for you, you can **generate it in code before sending it to the database**, because you can be quite certain it will be unique.
|
||||
|
||||
/// note | Technical Details
|
||||
|
||||
Because the number of possible UUIDs is so large (2^128), the probability of generating the same UUID version 4 (the random ones) twice is very low.
|
||||
|
||||
If you had 103 trillion version 4 UUIDs stored in the database, the probability of generating a duplicated new one is one in a billion. 🤓
|
||||
|
||||
///
|
||||
|
||||
For the same reason, if you decided to migrate your database, combine it with another database and mix records, etc. you would most probably be able to **just use the same UUIDs** you had originally.
|
||||
|
||||
/// warning
|
||||
|
||||
There's still a chance you could have a collision, but it's very low. In most cases you could assume you wouldn't have it, but it would be good to be prepared for it.
|
||||
|
||||
///
|
||||
|
||||
### UUIDs Prevent Information Leakage
|
||||
|
||||
Because UUIDs version 4 are **random**, you could give these IDs to the application users or to other systems, **without exposing information** about your application.
|
||||
|
||||
When using **auto-incremented integers** for primary keys, you could implicitly expose information about your system. For example, someone could create a new hero, and by getting the hero ID `20` **they would know that you have 20 heroes** in your system (or even less, if some heroes were already deleted).
|
||||
|
||||
### UUID Storage
|
||||
|
||||
Because UUIDs are 16 bytes, they would **consume more space** in the database than a smaller auto-incremented integer (commonly 4 bytes).
|
||||
|
||||
Depending on the database you use, UUIDs could have **better or worse performance**. If you are concerned about that, you should check the documentation for the specific database.
|
||||
|
||||
SQLite doesn't have a specific UUID type, so it will store the UUID as a string. Other databases like Postgres have a specific UUID type which would result in better performance and space usage than strings.
|
||||
|
||||
## Models with UUIDs
|
||||
|
||||
To use UUIDs as primary keys we need to import `uuid`, which is part of the Python standard library (we don't have to install anything) and use `uuid.UUID` as the **type** for the ID field.
|
||||
|
||||
We also want the Python code to **generate a new UUID** when creating a new instance, so we use `default_factory`.
|
||||
|
||||
The parameter `default_factory` takes a function (or in general, a "<abbr title="Something that can be called as a function.">callable</abbr>"). This function will be **called when creating a new instance** of the model and the value returned by the function will be used as the default value for the field.
|
||||
|
||||
For the function in `default_factory` we pass `uuid.uuid4`, which is a function that generates a **new UUID version 4**.
|
||||
|
||||
/// tip
|
||||
|
||||
We don't call `uuid.uuid4()` ourselves in the code (we don't put the parenthesis). Instead, we pass the function itself, just `uuid.uuid4`, so that SQLModel can call it every time we create a new instance.
|
||||
|
||||
///
|
||||
|
||||
This means that the UUID will be generated in the Python code, **before sending the data to the database**.
|
||||
|
||||
{* ./docs_src/advanced/uuid/tutorial001_py310.py ln[1:10] hl[1,7] *}
|
||||
|
||||
Pydantic has support for <a href="https://docs.pydantic.dev/latest/api/standard_library_types/#uuid" class="external-link" target="_blank">`UUID` types</a>.
|
||||
|
||||
For the database, **SQLModel** internally uses <a href="https://docs.sqlalchemy.org/en/20/core/type_basics.html#sqlalchemy.types.Uuid" class="external-link" target="_blank">SQLAlchemy's `Uuid` type</a>.
|
||||
|
||||
### Create a Record with a UUID
|
||||
|
||||
When creating a `Hero` record, the `id` field will be **automatically populated** with a new UUID because we set `default_factory=uuid.uuid4`.
|
||||
|
||||
As `uuid.uuid4` will be called when creating the model instance, even before sending it to the database, we can **access and use the ID right away**.
|
||||
|
||||
And that **same ID (a UUID)** will be saved in the database.
|
||||
|
||||
{* ./docs_src/advanced/uuid/tutorial001_py310.py ln[23:34] hl[25,27,29,34] *}
|
||||
|
||||
### Select a Hero
|
||||
|
||||
We can do the same operations we could do with other fields.
|
||||
|
||||
For example we can **select a hero by ID**:
|
||||
|
||||
{* ./docs_src/advanced/uuid/tutorial001_py310.py ln[37:54] hl[49] *}
|
||||
|
||||
/// tip
|
||||
|
||||
Even if a database like SQLite stores the UUID as a string, we can select and run comparisons using a Python UUID object and it will work.
|
||||
|
||||
SQLModel (actually SQLAlchemy) will take care of making it work. ✨
|
||||
|
||||
///
|
||||
|
||||
#### Select with `session.get()`
|
||||
|
||||
We could also select by ID with `session.get()`:
|
||||
|
||||
{* ./docs_src/advanced/uuid/tutorial002_py310.py ln[37:53] hl[49] *}
|
||||
|
||||
The same way as with other fields, we could update, delete, etc. 🚀
|
||||
|
||||
### Run the program
|
||||
|
||||
If you run the program, you will see the **UUID** generated in the Python code, and then the record **saved in the database with the same UUID**.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ python app.py
|
||||
|
||||
// Some boilerplate and previous output omitted 😉
|
||||
|
||||
// In SQLite, the UUID will be stored as a string
|
||||
// other DBs like Postgres have a specific UUID type
|
||||
CREATE TABLE hero (
|
||||
id CHAR(32) NOT NULL,
|
||||
name VARCHAR NOT NULL,
|
||||
secret_name VARCHAR NOT NULL,
|
||||
age INTEGER,
|
||||
PRIMARY KEY (id)
|
||||
)
|
||||
|
||||
// Before saving in the DB we already have the UUID
|
||||
The hero before saving in the DB
|
||||
name='Deadpond' secret_name='Dive Wilson' id=UUID('0e44c1a6-88d3-4a35-8b8a-307faa2def28') age=None
|
||||
The hero ID was already set
|
||||
0e44c1a6-88d3-4a35-8b8a-307faa2def28
|
||||
|
||||
// The SQL statement to insert the record uses our UUID
|
||||
INSERT INTO hero (id, name, secret_name, age) VALUES (?, ?, ?, ?)
|
||||
('0e44c1a688d34a358b8a307faa2def28', 'Deadpond', 'Dive Wilson', None)
|
||||
|
||||
// And indeed, the record was saved with the UUID we created 😎
|
||||
After saving in the DB
|
||||
age=None id=UUID('0e44c1a6-88d3-4a35-8b8a-307faa2def28') name='Deadpond' secret_name='Dive Wilson'
|
||||
|
||||
// Now we create a new hero (to select it in a bit)
|
||||
Created hero:
|
||||
age=None id=UUID('9d90d186-85db-4eaa-891a-def7b4ae2dab') name='Spider-Boy' secret_name='Pedro Parqueador'
|
||||
Created hero ID:
|
||||
9d90d186-85db-4eaa-891a-def7b4ae2dab
|
||||
|
||||
// And now we select it
|
||||
Selected hero:
|
||||
age=None id=UUID('9d90d186-85db-4eaa-891a-def7b4ae2dab') name='Spider-Boy' secret_name='Pedro Parqueador'
|
||||
Selected hero ID:
|
||||
9d90d186-85db-4eaa-891a-def7b4ae2dab
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## Learn More
|
||||
|
||||
You can learn more about **UUIDs** in:
|
||||
|
||||
* The official <a href="https://docs.python.org/3/library/uuid.html" class="external-link" target="_blank">Python docs for UUID</a>.
|
||||
* The <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier" class="external-link" target="_blank">Wikipedia for UUID</a>.
|
||||
@ -4,43 +4,49 @@ First, you might want to see the basic ways to [help SQLModel and get help](help
|
||||
|
||||
## Developing
|
||||
|
||||
If you already cloned the <a href="https://github.com/fastapi/sqlmodel" class="external-link" target="_blank">sqlmodel repository</a> and you want to deep dive in the code, here are some guidelines to set up your environment.
|
||||
If you already cloned the repository and you know that you need to deep dive in the code, here are some guidelines to set up your environment.
|
||||
|
||||
### Virtual Environment
|
||||
### Poetry
|
||||
|
||||
Follow the instructions to create and activate a [virtual environment](virtual-environments.md){.internal-link target=_blank} for the internal code of `sqlmodel`.
|
||||
**SQLModel** uses <a href="https://python-poetry.org/" class="external-link" target="_blank">Poetry</a> to build, package, and publish the project.
|
||||
|
||||
### Install Requirements Using `pip`
|
||||
You can learn how to install it in the <a href="https://python-poetry.org/docs/#installation" class="external-link" target="_blank">Poetry docs</a>.
|
||||
|
||||
After activating the environment, install the required packages:
|
||||
After having Poetry available, you can install the development dependencies:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install -r requirements.txt
|
||||
$ poetry install
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
It will install all the dependencies and your local SQLModel in your local environment.
|
||||
It will also create a virtual environment automatically and will install all the dependencies and your local SQLModel in it.
|
||||
|
||||
### Using your Local SQLModel
|
||||
### Poetry Shell
|
||||
|
||||
If you create a Python file that imports and uses SQLModel, and run it with the Python from your local environment, it will use your cloned local SQLModel source code.
|
||||
To use your current environment, and to have access to all the tools in it (for example `pytest` for the tests) enter into a Poetry Shell:
|
||||
|
||||
And if you update that local SQLModel source code when you run that Python file again, it will use the fresh version of SQLModel you just edited.
|
||||
<div class="termy">
|
||||
|
||||
That way, you don't have to "install" your local version to be able to test every change.
|
||||
```console
|
||||
$ poetry shell
|
||||
```
|
||||
|
||||
/// note | "Technical Details"
|
||||
</div>
|
||||
|
||||
This only happens when you install using this included `requirements.txt` instead of running `pip install sqlmodel` directly.
|
||||
That will set up the environment variables needed and start a new shell with them.
|
||||
|
||||
That is because inside the `requirements.txt` file, the local version of SQLModel is marked to be installed in "editable" mode, with the `-e` option.
|
||||
#### Using your local SQLModel
|
||||
|
||||
///
|
||||
If you create a Python file that imports and uses SQLModel, and run it with the Python from your local Poetry environment, it will use your local SQLModel source code.
|
||||
|
||||
And if you update that local SQLModel source code, when you run that Python file again, it will use the fresh version of SQLModel you just edited.
|
||||
|
||||
Poetry takes care of making that work. But of course, it will only work in the current Poetry environment, if you install standard SQLModel in another environment (not from the source in the GitHub repo), that will use the standard SQLModel, not your custom version.
|
||||
|
||||
### Format
|
||||
|
||||
@ -56,92 +62,9 @@ $ bash scripts/format.sh
|
||||
|
||||
It will also auto-sort all your imports.
|
||||
|
||||
## Tests
|
||||
|
||||
There is a script that you can run locally to test all the code and generate coverage reports in HTML:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ bash scripts/test-cov-html.sh
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing.
|
||||
|
||||
## Docs
|
||||
|
||||
First, make sure you set up your environment as described above, that will install all the requirements.
|
||||
|
||||
### Docs Live
|
||||
|
||||
During local development, there is a script that builds the site and checks for any changes, live-reloading:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ python ./scripts/docs.py live
|
||||
|
||||
<span style="color: green;">[INFO]</span> Serving on http://127.0.0.1:8008
|
||||
<span style="color: green;">[INFO]</span> Start watching changes
|
||||
<span style="color: green;">[INFO]</span> Start detecting changes
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
It will serve the documentation on `http://127.0.0.1:8008`.
|
||||
|
||||
That way, you can edit the documentation/source files and see the changes live.
|
||||
|
||||
/// tip
|
||||
|
||||
Alternatively, you can perform the same steps that scripts does manually.
|
||||
|
||||
Go into the docs director at `docs/`:
|
||||
|
||||
```console
|
||||
$ cd docs/
|
||||
```
|
||||
|
||||
Then run `mkdocs` in that directory:
|
||||
|
||||
```console
|
||||
$ mkdocs serve --dev-addr 8008
|
||||
```
|
||||
|
||||
///
|
||||
|
||||
#### Typer CLI (Optional)
|
||||
|
||||
The instructions here show you how to use the script at `./scripts/docs.py` with the `python` program directly.
|
||||
|
||||
But you can also use <a href="https://typer.tiangolo.com/typer-cli/" class="external-link" target="_blank">Typer CLI</a>, and you will get autocompletion in your terminal for the commands after installing completion.
|
||||
|
||||
If you install Typer CLI, you can install completion with:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ typer --install-completion
|
||||
|
||||
zsh completion installed in /home/user/.bashrc.
|
||||
Completion will take effect once you restart the terminal.
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
### Docs Structure
|
||||
|
||||
The documentation uses <a href="https://www.mkdocs.org/" class="external-link" target="_blank">MkDocs</a>.
|
||||
|
||||
And there are extra tools/scripts in place in `./scripts/docs.py`.
|
||||
|
||||
/// tip
|
||||
|
||||
You don't need to see the code in `./scripts/docs.py`, you just use it in the command line.
|
||||
|
||||
///
|
||||
The documentation uses <a href="https://www.mkdocs.org/" class="external-link" target="_blank">MkDocs</a> with <a href="https://squidfunk.github.io/mkdocs-material/" class="external-link" target="_blank">Material for MkDocs</a>.
|
||||
|
||||
All the documentation is in Markdown format in the directory `./docs`.
|
||||
|
||||
@ -153,12 +76,49 @@ In fact, those blocks of code are not written inside the Markdown, they are Pyth
|
||||
|
||||
And those Python files are included/injected in the documentation when generating the site.
|
||||
|
||||
### Docs for Tests
|
||||
### Docs for tests
|
||||
|
||||
Most of the tests actually run against the example source files in the documentation.
|
||||
|
||||
This helps to make sure that:
|
||||
This helps making sure that:
|
||||
|
||||
* The documentation is up-to-date.
|
||||
* The documentation is up to date.
|
||||
* The documentation examples can be run as is.
|
||||
* Most of the features are covered by the documentation, ensured by test coverage.
|
||||
|
||||
During local development, there is a script that builds the site and checks for any changes, live-reloading:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ bash scripts/docs-live.sh
|
||||
|
||||
<span style="color: green;">[INFO]</span> - Building documentation...
|
||||
<span style="color: green;">[INFO]</span> - Cleaning site directory
|
||||
<span style="color: green;">[INFO]</span> - Documentation built in 2.74 seconds
|
||||
<span style="color: green;">[INFO]</span> - Serving on http://127.0.0.1:8008
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
It will serve the documentation on `http://127.0.0.1:8008`.
|
||||
|
||||
That way, you can edit the documentation/source files and see the changes live.
|
||||
|
||||
## Tests
|
||||
|
||||
There is a script that you can run locally to test all the code and generate coverage reports in HTML:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ bash scripts/test.sh
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
This command generates a directory `./htmlcov/`, if you open the file `./htmlcov/index.html` in your browser, you can explore interactively the regions of code that are covered by the tests, and notice if there is any region missing.
|
||||
|
||||
## Thanks
|
||||
|
||||
Thanks for contributing! ☕
|
||||
|
||||
@ -8,10 +8,6 @@
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.termy .linenos {
|
||||
display: none;
|
||||
}
|
||||
|
||||
a.external-link::after {
|
||||
/* \00A0 is a non-breaking space
|
||||
to make the mark be on the same line as the link
|
||||
@ -29,43 +25,3 @@ a.internal-link::after {
|
||||
.shadow {
|
||||
box-shadow: 5px 5px 10px #999;
|
||||
}
|
||||
|
||||
.user-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.user-list-center {
|
||||
justify-content: space-evenly;
|
||||
}
|
||||
|
||||
.user {
|
||||
margin: 1em;
|
||||
min-width: 7em;
|
||||
}
|
||||
|
||||
.user .avatar-wrapper {
|
||||
width: 80px;
|
||||
height: 80px;
|
||||
margin: 10px auto;
|
||||
overflow: hidden;
|
||||
border-radius: 50%;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.user .avatar-wrapper img {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
}
|
||||
|
||||
.user .title {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.user .count {
|
||||
font-size: 80%;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@ -26,8 +26,6 @@
|
||||
position: relative;
|
||||
-webkit-box-sizing: border-box;
|
||||
box-sizing: border-box;
|
||||
/* Custom line-height */
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
[data-termynal]:before {
|
||||
|
||||
@ -1,12 +1,9 @@
|
||||
# Intro to Databases
|
||||
|
||||
/// info
|
||||
!!! info
|
||||
Are you a seasoned developer and already know everything about databases? 🤓
|
||||
|
||||
Are you a seasoned developer and already know everything about databases? 🤓
|
||||
|
||||
Then you can skip to the next sections right away.
|
||||
|
||||
///
|
||||
Then you can skip to the [Tutorial - User Guide: First Steps](tutorial/index.md){.internal-link target=_blank} right away.
|
||||
|
||||
If you don't know everything about databases, here's a quick overview.
|
||||
|
||||
@ -20,11 +17,8 @@ So, what is a database?
|
||||
|
||||
A **database** is a system to store and manage data in a structured and very efficient way.
|
||||
|
||||
/// tip
|
||||
|
||||
It's very common to abbreviate the word "database" as **"DB"**.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
It's very common to abbreviate the word "database" as **"DB"**.
|
||||
|
||||
As there's a lot of information about databases, and it can get very technical and academic, I'll give you a quick overview about some of the main concepts here.
|
||||
|
||||
@ -34,11 +28,8 @@ I'll even tell you a bit about different types of databases, including the ones
|
||||
|
||||
When starting to program, it might **not be obvious** why having a database apart from the code for your program is a **good idea**. Let's start with that.
|
||||
|
||||
/// tip
|
||||
|
||||
If that's obvious to you, just continue in the next section below. 👇
|
||||
|
||||
///
|
||||
!!! tip
|
||||
If that's obvious to you, just continue in the next section below. 👇
|
||||
|
||||
In your code you already have **variables**, **dictionaries**, **lists**, etc. They all store **data** in some way already. Why would you need to have a separate database?
|
||||
|
||||
@ -68,7 +59,7 @@ There are many databases of many types.
|
||||
|
||||
A database could be a single file called `heroes.db`, managed with code in a very efficient way. An example would be SQLite, more about that on a bit.
|
||||
|
||||

|
||||

|
||||
|
||||
### A server database
|
||||
|
||||
@ -80,11 +71,11 @@ In this case, your code would talk to this server application instead of reading
|
||||
|
||||
The database could be located in a different server/machine:
|
||||
|
||||

|
||||

|
||||
|
||||
Or the database could be located in the same server/machine:
|
||||
|
||||

|
||||

|
||||
|
||||
The most important aspect of these types of databases is that **your code doesn't read or modify** the files containing the data directly.
|
||||
|
||||
@ -98,7 +89,7 @@ In some cases, the database could even be a group of server applications running
|
||||
|
||||
In this case, your code would talk to one or more of these server applications running on different machines.
|
||||
|
||||

|
||||

|
||||
|
||||
Most of the databases that work as server applications also support multiple servers in one way or another.
|
||||
|
||||
@ -137,7 +128,7 @@ If we worked with a single table to store our heroes, it could be like this:
|
||||
<th>id</th><th>name</th><th>secret_name</th><th>age</th><th>team</th><th>headquarters</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1</td><td>Deadpond</td><td>Dive Wilson</td><td>null</td><td>Z-Factor</td><td>Sister Margaret's Bar</td>
|
||||
<td>1</td><td>Deadpond</td><td>Dive Wilson</td><td>null</td><td>Z-Factor</td><td>Sister Margaret’s Bar</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>2</td><td>Spider-Boy</td><td>Pedro Parqueador</td><td>null</td><td>Preventers</td><td>Sharp Tower</td>
|
||||
@ -166,7 +157,7 @@ We could end up with inconsistent information, having one place saying "Prevente
|
||||
<th>id</th><th>name</th><th>secret_name</th><th>age</th><th>team</th><th>headquarters</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1</td><td>Deadpond</td><td>Dive Wilson</td><td>null</td><td>Z-Force</td><td>Sister Margaret's Bar</td>
|
||||
<td>1</td><td>Deadpond</td><td>Dive Wilson</td><td>null</td><td>Z-Force</td><td>Sister Margaret’s Bar</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>2</td><td>Spider-Boy</td><td>Pedro Parqueador</td><td>null</td><td>Preventers</td><td>Preventers Tower ✅</td>
|
||||
@ -185,7 +176,7 @@ We could forget the name of the team and end up adding "Mahjong" with an invalid
|
||||
<th>id</th><th>name</th><th>secret_name</th><th>age</th><th>team</th><th>headquarters</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>1</td><td>Deadpond</td><td>Dive Wilson</td><td>null</td><td>Z-Force</td><td>Sister Margaret's Bar</td>
|
||||
<td>1</td><td>Deadpond</td><td>Dive Wilson</td><td>null</td><td>Z-Force</td><td>Sister Margaret’s Bar</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>2</td><td>Spider-Boy</td><td>Pedro Parqueador</td><td>null</td><td>Preventers</td><td>Preventers Tower</td>
|
||||
@ -194,7 +185,7 @@ We could forget the name of the team and end up adding "Mahjong" with an invalid
|
||||
<td>3</td><td>Rusty-Man</td><td>Tommy Sharp</td><td>48</td><td>Preventers</td><td>Sharp Tower</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>4</td><td>Mahjong</td><td>Neena Thurgirl</td><td>31</td><td>Y-Force 🚨</td><td>Sister Margaret's Bar</td>
|
||||
<td>4</td><td>Mahjong</td><td>Neena Thurgirl</td><td>31</td><td>Y-Force 🚨</td><td>Sister Margaret’s Bar</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@ -216,7 +207,7 @@ The table for the teams could look like this:
|
||||
<td>1</td><td>Preventers</td><td>Sharp Tower</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>2</td><td>Z-Force</td><td>Sister Margaret's Bar</td>
|
||||
<td>2</td><td>Z-Force</td><td>Sister Margaret’s Bar</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@ -257,7 +248,7 @@ For example, the table for the teams has the ID `1` for the team `Preventers` an
|
||||
|
||||
As these **primary key** IDs can uniquely identify each row on the table for teams, we can now go to the table for heroes and refer to those IDs in the table for teams.
|
||||
|
||||

|
||||
<img alt="table relationships" src="/img/databases/relationships.svg">
|
||||
|
||||
So, in the table for heroes, we use the `team_id` column to define a relationship to the *foreign* table for teams. Each value in the `team_id` column on the table with heroes will be the same value as the `id` column of one row in the table with teams.
|
||||
|
||||
@ -317,11 +308,8 @@ Next, it receives the data and puts it in Python objects that you can continue t
|
||||
|
||||
I'll tell you more about SQL, SQLModel, how to use them, and how they are related in the next sections.
|
||||
|
||||
/// info | Technical Details
|
||||
|
||||
SQLModel is built on top of SQLAlchemy. It is, in fact, just <a href="https://www.sqlalchemy.org/" class="external-link" target="_blank">SQLAlchemy</a> and <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> mixed together with some sugar on top.
|
||||
|
||||
///
|
||||
!!! info "Technical Details"
|
||||
SQLModel is built on top of SQLAlchemy. It is, in fact, just <a href="https://www.sqlalchemy.org/" class="external-link" target="_blank">SQLAlchemy</a> and <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> mixed together with some sugar on top.
|
||||
|
||||
## NoSQL Databases
|
||||
|
||||
|
||||
@ -172,11 +172,8 @@ The difference in the final SQL statement is subtle, but it changes the meaning
|
||||
SELECT * FROM hero WHERE id = "2; DROP TABLE hero;";
|
||||
```
|
||||
|
||||
/// tip
|
||||
|
||||
Notice the double quotes (`"`) making it a string instead of more raw SQL.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Notice the double quotes (`"`) making it a string instead of more raw SQL.
|
||||
|
||||
The database will not find any record with that ID:
|
||||
|
||||
@ -190,11 +187,8 @@ Then your code will continue to execute and calmly tell the user that it couldn'
|
||||
|
||||
But we never deleted the `hero` table. 🎉
|
||||
|
||||
/// info
|
||||
|
||||
Of course, there are also other ways to do SQL data sanitization without using a tool like **SQLModel**, but it's still a nice feature you get by default.
|
||||
|
||||
///
|
||||
!!! info
|
||||
Of course, there are also other ways to do SQL data sanitization without using a tool like **SQLModel**, but it's still a nice feature you get by default.
|
||||
|
||||
### Editor Support
|
||||
|
||||
@ -236,7 +230,8 @@ database.execute(
|
||||
).all()
|
||||
```
|
||||
|
||||
{class="shadow"}
|
||||
<img class="shadow" src="/img/db-to-code/autocompletion01.png">
|
||||
|
||||
|
||||
## ORMs and SQL
|
||||
|
||||
@ -279,7 +274,7 @@ For example this **Relation** or table:
|
||||
|
||||
* **Mapper**: this comes from Math, when there's something that can convert from some set of things to another, that's called a "**mapping function**". That's where the **Mapper** comes from.
|
||||
|
||||

|
||||

|
||||
|
||||
We could also write a **mapping function** in Python that converts from the *set of lowercase letters* to the *set of uppercase letters*, like this:
|
||||
|
||||
@ -296,11 +291,8 @@ There are many ORMs available apart from **SQLModel**, you can read more about s
|
||||
|
||||
## SQL Table Names
|
||||
|
||||
/// info | Technical Background
|
||||
|
||||
This is a bit of boring background for SQL purists. Feel free to skip this section. 😉
|
||||
|
||||
///
|
||||
!!! info "Technical Background"
|
||||
This is a bit of boring background for SQL purists. Feel free to skip this section. 😉
|
||||
|
||||
When working with pure SQL, it's common to name the tables in plural. So, the table would be named `heroes` instead of `hero`, because it could contain multiple rows, each with one hero.
|
||||
|
||||
@ -312,8 +304,5 @@ You will see **your own code** a lot more than the internal table names, so it's
|
||||
|
||||
So, to keep things consistent, I'll keep using the same table names that **SQLModel** would have generated.
|
||||
|
||||
/// tip
|
||||
|
||||
You can also override the table name. You can read about it in the Advanced User Guide.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
You can also override the table name. You can read about it in the Advanced User Guide.
|
||||
|
||||
@ -1,300 +0,0 @@
|
||||
# Environment Variables
|
||||
|
||||
Before we jump into code, let's cover a bit some of the **basics** that we'll need to understand how to work with Python (and programming) in general. Let's check a bit about **environment variables**.
|
||||
|
||||
/// tip
|
||||
|
||||
If you already know what "environment variables" are and how to use them, feel free to skip this.
|
||||
|
||||
///
|
||||
|
||||
An environment variable (also known as "**env var**") is a variable that lives **outside** of the Python code, in the **operating system**, and could be read by your Python code (or by other programs as well).
|
||||
|
||||
Environment variables could be useful for handling application **settings**, as part of the **installation** of Python, etc.
|
||||
|
||||
## Create and Use Env Vars
|
||||
|
||||
You can **create** and use environment variables in the **shell (terminal)**, without needing Python:
|
||||
|
||||
//// tab | Linux, macOS, Windows Bash
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// You could create an env var MY_NAME with
|
||||
$ export MY_NAME="Wade Wilson"
|
||||
|
||||
// Then you could use it with other programs, like
|
||||
$ echo "Hello $MY_NAME"
|
||||
|
||||
Hello Wade Wilson
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows PowerShell
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Create an env var MY_NAME
|
||||
$ $Env:MY_NAME = "Wade Wilson"
|
||||
|
||||
// Use it with other programs, like
|
||||
$ echo "Hello $Env:MY_NAME"
|
||||
|
||||
Hello Wade Wilson
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
## Read env vars in Python
|
||||
|
||||
You could also create environment variables **outside** of Python, in the terminal (or with any other method), and then **read them in Python**.
|
||||
|
||||
For example you could have a file `main.py` with:
|
||||
|
||||
```Python hl_lines="3"
|
||||
import os
|
||||
|
||||
name = os.getenv("MY_NAME", "World")
|
||||
print(f"Hello {name} from Python")
|
||||
```
|
||||
|
||||
/// tip
|
||||
|
||||
The second argument to <a href="https://docs.python.org/3.8/library/os.html#os.getenv" class="external-link" target="_blank">`os.getenv()`</a> is the default value to return.
|
||||
|
||||
If not provided, it's `None` by default, here we provide `"World"` as the default value to use.
|
||||
|
||||
///
|
||||
|
||||
Then you could call that Python program:
|
||||
|
||||
//// tab | Linux, macOS, Windows Bash
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Here we don't set the env var yet
|
||||
$ python main.py
|
||||
|
||||
// As we didn't set the env var, we get the default value
|
||||
|
||||
Hello World from Python
|
||||
|
||||
// But if we create an environment variable first
|
||||
$ export MY_NAME="Wade Wilson"
|
||||
|
||||
// And then call the program again
|
||||
$ python main.py
|
||||
|
||||
// Now it can read the environment variable
|
||||
|
||||
Hello Wade Wilson from Python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows PowerShell
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Here we don't set the env var yet
|
||||
$ python main.py
|
||||
|
||||
// As we didn't set the env var, we get the default value
|
||||
|
||||
Hello World from Python
|
||||
|
||||
// But if we create an environment variable first
|
||||
$ $Env:MY_NAME = "Wade Wilson"
|
||||
|
||||
// And then call the program again
|
||||
$ python main.py
|
||||
|
||||
// Now it can read the environment variable
|
||||
|
||||
Hello Wade Wilson from Python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
As environment variables can be set outside of the code, but can be read by the code, and don't have to be stored (committed to `git`) with the rest of the files, it's common to use them for configurations or **settings**.
|
||||
|
||||
You can also create an environment variable only for a **specific program invocation**, that is only available to that program, and only for its duration.
|
||||
|
||||
To do that, create it right before the program itself, on the same line:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Create an env var MY_NAME in line for this program call
|
||||
$ MY_NAME="Wade Wilson" python main.py
|
||||
|
||||
// Now it can read the environment variable
|
||||
|
||||
Hello Wade Wilson from Python
|
||||
|
||||
// The env var no longer exists afterwards
|
||||
$ python main.py
|
||||
|
||||
Hello World from Python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
/// tip
|
||||
|
||||
You can read more about it at <a href="https://12factor.net/config" class="external-link" target="_blank">The Twelve-Factor App: Config</a>.
|
||||
|
||||
///
|
||||
|
||||
## Types and Validation
|
||||
|
||||
These environment variables can only handle **text strings**, as they are external to Python and have to be compatible with other programs and the rest of the system (and even with different operating systems, as Linux, Windows, macOS).
|
||||
|
||||
That means that **any value** read in Python from an environment variable **will be a `str`**, and any conversion to a different type or any validation has to be done in code.
|
||||
|
||||
## `PATH` Environment Variable
|
||||
|
||||
There is a **special** environment variable called **`PATH`** that is used by the operating systems (Linux, macOS, Windows) to find programs to run.
|
||||
|
||||
The value of the variable `PATH` is a long string that is made of directories separated by a colon `:` on Linux and macOS, and by a semicolon `;` on Windows.
|
||||
|
||||
For example, the `PATH` environment variable could look like this:
|
||||
|
||||
//// tab | Linux, macOS
|
||||
|
||||
```plaintext
|
||||
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
|
||||
```
|
||||
|
||||
This means that the system should look for programs in the directories:
|
||||
|
||||
* `/usr/local/bin`
|
||||
* `/usr/bin`
|
||||
* `/bin`
|
||||
* `/usr/sbin`
|
||||
* `/sbin`
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows
|
||||
|
||||
```plaintext
|
||||
C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32
|
||||
```
|
||||
|
||||
This means that the system should look for programs in the directories:
|
||||
|
||||
* `C:\Program Files\Python312\Scripts`
|
||||
* `C:\Program Files\Python312`
|
||||
* `C:\Windows\System32`
|
||||
|
||||
////
|
||||
|
||||
When you type a **command** in the terminal, the operating system **looks for** the program in **each of those directories** listed in the `PATH` environment variable.
|
||||
|
||||
For example, when you type `python` in the terminal, the operating system looks for a program called `python` in the **first directory** in that list.
|
||||
|
||||
If it finds it, then it will **use it**. Otherwise it keeps looking in the **other directories**.
|
||||
|
||||
### Installing Python and Updating the `PATH`
|
||||
|
||||
When you install Python, you might be asked if you want to update the `PATH` environment variable.
|
||||
|
||||
//// tab | Linux, macOS
|
||||
|
||||
Let's say you install Python and it ends up in a directory `/opt/custompython/bin`.
|
||||
|
||||
If you say yes to update the `PATH` environment variable, then the installer will add `/opt/custompython/bin` to the `PATH` environment variable.
|
||||
|
||||
It could look like this:
|
||||
|
||||
```plaintext
|
||||
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin
|
||||
```
|
||||
|
||||
This way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one.
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows
|
||||
|
||||
Let's say you install Python and it ends up in a directory `C:\opt\custompython\bin`.
|
||||
|
||||
If you say yes to update the `PATH` environment variable, then the installer will add `C:\opt\custompython\bin` to the `PATH` environment variable.
|
||||
|
||||
```plaintext
|
||||
C:\Program Files\Python312\Scripts;C:\Program Files\Python312;C:\Windows\System32;C:\opt\custompython\bin
|
||||
```
|
||||
|
||||
This way, when you type `python` in the terminal, the system will find the Python program in `C:\opt\custompython\bin` (the last directory) and use that one.
|
||||
|
||||
////
|
||||
|
||||
This way, when you type `python` in the terminal, the system will find the Python program in `/opt/custompython/bin` (the last directory) and use that one.
|
||||
|
||||
So, if you type:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
//// tab | Linux, macOS
|
||||
|
||||
The system will **find** the `python` program in `/opt/custompython/bin` and run it.
|
||||
|
||||
It would be roughly equivalent to typing:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ /opt/custompython/bin/python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows
|
||||
|
||||
The system will **find** the `python` program in `C:\opt\custompython\bin\python` and run it.
|
||||
|
||||
It would be roughly equivalent to typing:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ C:\opt\custompython\bin\python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
This information will be useful when learning about [Virtual Environments](virtual-environments.md){.internal-link target=_blank}.
|
||||
|
||||
## Conclusion
|
||||
|
||||
With this you should have a basic understanding of what **environment variables** are and how to use them in Python.
|
||||
|
||||
You can also read more about them in the <a href="https://en.wikipedia.org/wiki/Environment_variable" class="external-link" target="_blank">Wikipedia for Environment Variable</a>.
|
||||
|
||||
In many cases it's not very obvious how environment variables would be useful and applicable right away. But they keep showing up in many different scenarios when you are developing, so it's good to know about them.
|
||||
|
||||
For example, you will need this information in the next section, about [Virtual Environments](virtual-environments.md).
|
||||
@ -36,10 +36,17 @@ You will get completion for everything while writing the **minimum** amount of c
|
||||
|
||||
You won't need to keep guessing the types of different attributes in your models, if they could be `None`, etc. Your editor will be able to help you with everything because **SQLModel** is based on **standard Python type annotations**.
|
||||
|
||||
**SQLModel** adopts <a href="https://peps.python.org/pep-0681/" class="external-link" target="_blank">PEP 681</a> for Python type annotations to ensure the **best developer experience**, so you will get inline errors and autocompletion even while creating new model instances.
|
||||
**SQLModel** even adopts currently <a href="https://github.com/microsoft/pyright/blob/main/specs/dataclass_transforms.md" class="external-link" target="_blank">in development standards</a> for Python type annotations to ensure the **best developer experience**, so you will get inline errors and autocompletion even while creating new model instances.
|
||||
|
||||
<img class="shadow" src="/img/index/autocompletion01.png">
|
||||
|
||||
!!! info
|
||||
Don't worry, adopting this in-development standard only affects/improves editor support.
|
||||
|
||||
It doesn't affect performance or correctness. And if the in-progress standard was deprecated your code won't be affected.
|
||||
|
||||
Meanwhile, you will get inline errors (like type checks) and autocompletion on places you wouldn't get with any other library. 🎉
|
||||
|
||||
## Short
|
||||
|
||||
**SQLModel** has **sensible defaults** for everything, with **optional configurations** everywhere.
|
||||
|
||||
34
docs/help.md
@ -22,13 +22,13 @@ You can subscribe to the (infrequent) <a href="https://fastapi.tiangolo.com/news
|
||||
|
||||
## Star **SQLModel** in GitHub
|
||||
|
||||
You can "star" SQLModel in GitHub (clicking the star button at the top right): <a href="https://github.com/fastapi/sqlmodel" class="external-link" target="_blank">https://github.com/fastapi/sqlmodel</a>. ⭐️
|
||||
You can "star" SQLModel in GitHub (clicking the star button at the top right): <a href="https://github.com/tiangolo/sqlmodel" class="external-link" target="_blank">https://github.com/tiangolo/sqlmodel</a>. ⭐️
|
||||
|
||||
By adding a star, other users will be able to find it more easily and see that it has been already useful for others.
|
||||
|
||||
## Watch the GitHub repository for releases
|
||||
|
||||
You can "watch" SQLModel in GitHub (clicking the "watch" button at the top right): <a href="https://github.com/fastapi/sqlmodel" class="external-link" target="_blank">https://github.com/fastapi/sqlmodel</a>. 👀
|
||||
You can "watch" SQLModel in GitHub (clicking the "watch" button at the top right): <a href="https://github.com/tiangolo/sqlmodel" class="external-link" target="_blank">https://github.com/tiangolo/sqlmodel</a>. 👀
|
||||
|
||||
There you can select "Releases only".
|
||||
|
||||
@ -54,7 +54,7 @@ You can:
|
||||
|
||||
## Tweet about **SQLModel**
|
||||
|
||||
<a href="https://twitter.com/compose/tweet?text=I'm loving SQLModel because... https://github.com/fastapi/sqlmodel cc: @tiangolo" class="external-link" target="_blank">Tweet about **SQLModel**</a> and let me and others know why you like it. 🎉
|
||||
<a href="https://twitter.com/compose/tweet?text=I'm loving SQLModel because... https://github.com/tiangolo/sqlmodel cc: @tiangolo" class="external-link" target="_blank">Tweet about **SQLModel**</a> and let me and others know why you like it. 🎉
|
||||
|
||||
I love to hear about how **SQLModel** is being used, what you have liked in it, in which project/company are you using it, etc.
|
||||
|
||||
@ -62,8 +62,8 @@ I love to hear about how **SQLModel** is being used, what you have liked in it,
|
||||
|
||||
You can try and help others with their questions in:
|
||||
|
||||
* <a href="https://github.com/fastapi/sqlmodel/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aunanswered" class="external-link" target="_blank">GitHub Discussions</a>
|
||||
* <a href="https://github.com/fastapi/sqlmodel/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Aquestion+-label%3Aanswered+" class="external-link" target="_blank">GitHub Issues</a>
|
||||
* <a href="https://github.com/tiangolo/sqlmodel/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aunanswered" class="external-link" target="_blank">GitHub Discussions</a>
|
||||
* <a href="https://github.com/tiangolo/sqlmodel/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Aquestion+-label%3Aanswered+" class="external-link" target="_blank">GitHub Issues</a>
|
||||
|
||||
In many cases you might already know the answer for those questions. 🤓
|
||||
|
||||
@ -112,7 +112,7 @@ If they reply, there's a high chance you would have solved their problem, congra
|
||||
|
||||
## Watch the GitHub repository
|
||||
|
||||
You can "watch" SQLModel in GitHub (clicking the "watch" button at the top right): <a href="https://github.com/fastapi/sqlmodel" class="external-link" target="_blank">https://github.com/fastapi/sqlmodel</a>. 👀
|
||||
You can "watch" SQLModel in GitHub (clicking the "watch" button at the top right): <a href="https://github.com/tiangolo/sqlmodel" class="external-link" target="_blank">https://github.com/tiangolo/sqlmodel</a>. 👀
|
||||
|
||||
If you select "Watching" instead of "Releases only" you will receive notifications when someone creates a new issue or question. You can also specify that you only want to be notified about new issues, or discussions, or PRs, etc.
|
||||
|
||||
@ -120,7 +120,7 @@ Then you can try and help them solve those questions.
|
||||
|
||||
## Ask Questions
|
||||
|
||||
You can <a href="https://github.com/fastapi/sqlmodel/discussions/new?category=questions" class="external-link" target="_blank">create a new question</a> in the GitHub repository, for example to:
|
||||
You can <a href="https://github.com/tiangolo/sqlmodel/discussions/new?category=questions" class="external-link" target="_blank">create a new question</a> in the GitHub repository, for example to:
|
||||
|
||||
* Ask a **question** or ask about a **problem**.
|
||||
* Suggest a new **feature**.
|
||||
@ -157,15 +157,12 @@ And if there's any other style or consistency need, I'll ask directly for that,
|
||||
|
||||
* Then **comment** saying that you did that, that's how I will know you really checked it.
|
||||
|
||||
/// info
|
||||
!!! info
|
||||
Unfortunately, I can't simply trust PRs that just have several approvals.
|
||||
|
||||
Unfortunately, I can't simply trust PRs that just have several approvals.
|
||||
Several times it has happened that there are PRs with 3, 5 or more approvals, probably because the description is appealing, but when I check the PRs, they are actually broken, have a bug, or don't solve the problem they claim to solve. 😅
|
||||
|
||||
Several times it has happened that there are PRs with 3, 5 or more approvals, probably because the description is appealing, but when I check the PRs, they are actually broken, have a bug, or don't solve the problem they claim to solve. 😅
|
||||
|
||||
So, it's really important that you actually read and run the code, and let me know in the comments that you did. 🤓
|
||||
|
||||
///
|
||||
So, it's really important that you actually read and run the code, and let me know in the comments that you did. 🤓
|
||||
|
||||
* If the PR can be simplified in a way, you can ask for that, but there's no need to be too picky, there might be a lot of subjective points of view (and I will have my own as well 🙈), so it's better if you can focus on the fundamental things.
|
||||
|
||||
@ -212,13 +209,10 @@ If you can help me with that, **you are helping me maintain SQLModel** and makin
|
||||
|
||||
Join the 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">FastAPI and Friends Discord chat server</a> 👥 and hang out with others in the community. There's a `#sqlmodel` channel.
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
For questions, ask them in <a href="https://github.com/tiangolo/sqlmodel/discussions/new?category=questions" class="external-link" target="_blank">GitHub Discussions</a>, there's a much better chance you will receive help there.
|
||||
|
||||
For questions, ask them in <a href="https://github.com/fastapi/sqlmodel/discussions/new?category=questions" class="external-link" target="_blank">GitHub Discussions</a>, there's a much better chance you will receive help there.
|
||||
|
||||
Use the chat only for other general conversations.
|
||||
|
||||
///
|
||||
Use the chat only for other general conversations.
|
||||
|
||||
### Don't use the chat for questions
|
||||
|
||||
|
||||
@ -115,7 +115,7 @@
|
||||
<mxCell id="56" value="<span style="font-family: &#34;roboto&#34; ; font-size: 18px">Z-Force</span>" style="shape=partialRectangle;html=1;whiteSpace=wrap;connectable=0;top=0;left=0;bottom=0;right=0;overflow=hidden;strokeColor=none;fillColor=none;" parent="54" vertex="1">
|
||||
<mxGeometry x="50" width="110" height="50" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="57" value="<p style="background-color: rgb(255 , 255 , 255) ; line-height: 19px"><font face="Roboto" data-font-src="https://fonts.googleapis.com/css?family=Roboto" style="font-size: 18px">Sister Margaret's Bar</font></p>" style="shape=partialRectangle;html=1;whiteSpace=wrap;connectable=0;top=0;left=0;bottom=0;right=0;overflow=hidden;strokeColor=none;fillColor=none;" parent="54" vertex="1">
|
||||
<mxCell id="57" value="<p style="background-color: rgb(255 , 255 , 255) ; line-height: 19px"><font face="Roboto" data-font-src="https://fonts.googleapis.com/css?family=Roboto" style="font-size: 18px">Sister Margaret’s Bar</font></p>" style="shape=partialRectangle;html=1;whiteSpace=wrap;connectable=0;top=0;left=0;bottom=0;right=0;overflow=hidden;strokeColor=none;fillColor=none;" parent="54" vertex="1">
|
||||
<mxGeometry x="160" width="200" height="50" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="66" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;strokeWidth=2;" parent="1" source="18" target="54" edge="1">
|
||||
|
||||
|
Before Width: | Height: | Size: 37 KiB After Width: | Height: | Size: 37 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 11 KiB |
@ -1,105 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
id="svg8"
|
||||
version="1.1"
|
||||
viewBox="0 0 848.54461 237.29972"
|
||||
height="237.29971mm"
|
||||
width="848.54462mm"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||
<defs
|
||||
id="defs2" />
|
||||
<metadata
|
||||
id="metadata5">
|
||||
<rdf:RDF>
|
||||
<cc:Work
|
||||
rdf:about="">
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<text
|
||||
id="text861"
|
||||
y="158.23088"
|
||||
x="204.64526"
|
||||
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-size:113.462px;line-height:1.25;font-family:Ubuntu;-inkscape-font-specification:'Ubuntu Bold';letter-spacing:0px;word-spacing:0px;fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:2.83655"
|
||||
xml:space="preserve"
|
||||
transform="scale(1.0209259,0.979503)"><tspan
|
||||
style="font-style:normal;font-variant:normal;font-weight:bold;font-stretch:normal;font-family:Ubuntu;-inkscape-font-specification:'Ubuntu Bold';fill:#ffffff;fill-opacity:1;stroke-width:2.83655"
|
||||
y="158.23088"
|
||||
x="204.64526"
|
||||
id="tspan859">SQLModel</tspan></text>
|
||||
<g
|
||||
id="g1074"
|
||||
transform="matrix(7.048594,0,0,6.7626049,42.411668,48.341116)">
|
||||
<g
|
||||
id="g1470">
|
||||
<rect
|
||||
style="fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:1.27225;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;stop-color:#000000"
|
||||
id="rect1457"
|
||||
width="15.627598"
|
||||
height="11.127809"
|
||||
x="3.6129446"
|
||||
y="3.9663849" />
|
||||
<g
|
||||
id="g1309-3"
|
||||
transform="translate(2.3451874e-4,7.0648327)">
|
||||
<path
|
||||
id="path1225-7"
|
||||
style="fill:#7e56c2;fill-opacity:1;stroke:none;stroke-width:1.82079;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;stop-color:#000000"
|
||||
d="M 12.164062,0.94726562 C 6.0622484,0.95386183 1.1299602,2.2428239 1.1328125,3.8300781 v 5.7617188 c -0.00281,1.5920051 4.9579969,2.8829331 11.0781255,2.8828121 6.119365,-1.6e-4 11.078978,-1.291006 11.076171,-2.8828121 V 3.8300781 C 23.289909,2.2382718 18.330304,0.94742553 12.210938,0.94726562 Z"
|
||||
transform="matrix(0.70540328,0,0,0.70540328,2.813504,1.2191569)" />
|
||||
<ellipse
|
||||
style="fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:1.28439;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;stop-color:#000000"
|
||||
id="path1225-2-5"
|
||||
cx="11.426781"
|
||||
cy="3.7396178"
|
||||
rx="7.8139534"
|
||||
ry="2.0326128" />
|
||||
</g>
|
||||
<g
|
||||
id="g1309"
|
||||
transform="translate(1.1725937e-4,1.6131871)">
|
||||
<path
|
||||
id="path1225"
|
||||
style="fill:#7e56c2;fill-opacity:1;stroke:none;stroke-width:1.82079;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;stop-color:#000000"
|
||||
d="M 12.164062,0.94726562 C 6.0622484,0.95386183 1.1299602,2.2428239 1.1328125,3.8300781 v 5.7617188 c -0.00281,1.5920051 4.9579969,2.8829331 11.0781255,2.8828121 6.119365,-1.6e-4 11.078978,-1.291006 11.076171,-2.8828121 V 3.8300781 C 23.289909,2.2382718 18.330304,0.94742553 12.210938,0.94726562 Z"
|
||||
transform="matrix(0.70540328,0,0,0.70540328,2.813504,1.2191569)" />
|
||||
<ellipse
|
||||
style="fill:#ffffff;fill-opacity:1;stroke:none;stroke-width:1.28439;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;stop-color:#000000"
|
||||
id="path1225-2"
|
||||
cx="11.426781"
|
||||
cy="3.7396178"
|
||||
rx="7.8139534"
|
||||
ry="2.0326128" />
|
||||
</g>
|
||||
<ellipse
|
||||
style="fill:#7e56c2;fill-opacity:1;stroke:none;stroke-width:1.28439;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;stop-color:#000000"
|
||||
id="path1225-2-9"
|
||||
cx="11.426898"
|
||||
cy="3.9663849"
|
||||
rx="7.8139534"
|
||||
ry="2.0326128" />
|
||||
<g
|
||||
id="g1391">
|
||||
<circle
|
||||
style="fill:#ffffff;stroke:none;stroke-width:0.638958;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;stop-color:#000000"
|
||||
id="path1149-1-2"
|
||||
cx="16.495272"
|
||||
cy="8.9521942"
|
||||
r="1.128226" />
|
||||
<circle
|
||||
style="fill:#ffffff;stroke:none;stroke-width:0.638958;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;stop-color:#000000"
|
||||
id="path1149-6-8-8"
|
||||
cx="16.495272"
|
||||
cy="14.40166"
|
||||
r="1.128226" />
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 4.6 KiB |
@ -1,15 +1,39 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||
<svg
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
|
||||
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
|
||||
id="svg8"
|
||||
version="1.1"
|
||||
viewBox="0 0 848.54461 237.29972"
|
||||
height="237.29971mm"
|
||||
width="848.54462mm"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
xmlns:svg="http://www.w3.org/2000/svg"
|
||||
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
|
||||
xmlns:cc="http://creativecommons.org/ns#"
|
||||
xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||
sodipodi:docname="logo-margin.svg"
|
||||
inkscape:version="1.0.2 (1.0.2+r75+1)">
|
||||
<sodipodi:namedview
|
||||
pagecolor="#ffffff"
|
||||
bordercolor="#666666"
|
||||
borderopacity="1"
|
||||
objecttolerance="10"
|
||||
gridtolerance="10"
|
||||
guidetolerance="10"
|
||||
inkscape:pageopacity="0"
|
||||
inkscape:pageshadow="2"
|
||||
inkscape:window-width="2434"
|
||||
inkscape:window-height="1412"
|
||||
id="namedview22"
|
||||
showgrid="false"
|
||||
inkscape:zoom="0.44294931"
|
||||
inkscape:cx="1603.5488"
|
||||
inkscape:cy="448.44039"
|
||||
inkscape:window-x="0"
|
||||
inkscape:window-y="0"
|
||||
inkscape:window-maximized="0"
|
||||
inkscape:current-layer="svg8" />
|
||||
<defs
|
||||
id="defs2" />
|
||||
<metadata
|
||||
@ -20,9 +44,17 @@
|
||||
<dc:format>image/svg+xml</dc:format>
|
||||
<dc:type
|
||||
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
|
||||
<dc:title />
|
||||
</cc:Work>
|
||||
</rdf:RDF>
|
||||
</metadata>
|
||||
<rect
|
||||
y="4.2351647e-22"
|
||||
x="0"
|
||||
height="237.29971"
|
||||
width="848.54462"
|
||||
id="rect824"
|
||||
style="opacity:0.98;fill:#ffffff;fill-opacity:1;stroke-width:0.514755" />
|
||||
<g
|
||||
id="g939"
|
||||
transform="translate(-23.453818,-6.0051303)">
|
||||
|
||||
|
Before Width: | Height: | Size: 4.8 KiB After Width: | Height: | Size: 5.8 KiB |
|
Before Width: | Height: | Size: 9.8 KiB |
|
Before Width: | Height: | Size: 87 KiB After Width: | Height: | Size: 83 KiB |
@ -103,7 +103,7 @@
|
||||
<mxCell id="56" value="<span style="font-family: &#34;roboto&#34; ; font-size: 18px">Z-Force</span>" style="shape=partialRectangle;html=1;whiteSpace=wrap;connectable=0;top=0;left=0;bottom=0;right=0;overflow=hidden;fillColor=#e1d5e7;strokeColor=#9673a6;" parent="54" vertex="1">
|
||||
<mxGeometry x="50" width="110" height="50" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="57" value="<p style="line-height: 19px"><font face="Roboto" data-font-src="https://fonts.googleapis.com/css?family=Roboto" style="font-size: 18px">Sister Margaret's Bar</font></p>" style="shape=partialRectangle;html=1;whiteSpace=wrap;connectable=0;top=0;left=0;bottom=0;right=0;overflow=hidden;fillColor=#e1d5e7;strokeColor=#9673a6;" parent="54" vertex="1">
|
||||
<mxCell id="57" value="<p style="line-height: 19px"><font face="Roboto" data-font-src="https://fonts.googleapis.com/css?family=Roboto" style="font-size: 18px">Sister Margaret’s Bar</font></p>" style="shape=partialRectangle;html=1;whiteSpace=wrap;connectable=0;top=0;left=0;bottom=0;right=0;overflow=hidden;fillColor=#e1d5e7;strokeColor=#9673a6;" parent="54" vertex="1">
|
||||
<mxGeometry x="160" width="200" height="50" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="69" value="<font face="Roboto" data-font-src="https://fonts.googleapis.com/css?family=Roboto" style="font-size: 18px">heroteamlink</font>" style="shape=table;html=1;whiteSpace=wrap;startSize=30;container=1;collapsible=0;childLayout=tableLayout;fontStyle=1;align=center;fillColor=#FFFFFF;swimlaneFillColor=#ffffff;" vertex="1" parent="1">
|
||||
|
||||
|
Before Width: | Height: | Size: 53 KiB After Width: | Height: | Size: 53 KiB |
@ -115,7 +115,7 @@
|
||||
<mxCell id="56" value="<span style="font-family: &#34;roboto&#34; ; font-size: 18px">Z-Force</span>" style="shape=partialRectangle;html=1;whiteSpace=wrap;connectable=0;top=0;left=0;bottom=0;right=0;overflow=hidden;" parent="54" vertex="1">
|
||||
<mxGeometry x="50" width="110" height="50" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="57" value="<p style="background-color: rgb(255 , 255 , 255) ; line-height: 19px"><font face="Roboto" data-font-src="https://fonts.googleapis.com/css?family=Roboto" style="font-size: 18px">Sister Margaret's Bar</font></p>" style="shape=partialRectangle;html=1;whiteSpace=wrap;connectable=0;top=0;left=0;bottom=0;right=0;overflow=hidden;" parent="54" vertex="1">
|
||||
<mxCell id="57" value="<p style="background-color: rgb(255 , 255 , 255) ; line-height: 19px"><font face="Roboto" data-font-src="https://fonts.googleapis.com/css?family=Roboto" style="font-size: 18px">Sister Margaret’s Bar</font></p>" style="shape=partialRectangle;html=1;whiteSpace=wrap;connectable=0;top=0;left=0;bottom=0;right=0;overflow=hidden;" parent="54" vertex="1">
|
||||
<mxGeometry x="160" width="200" height="50" as="geometry"/>
|
||||
</mxCell>
|
||||
<mxCell id="66" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;strokeWidth=2;" parent="1" source="18" target="54" edge="1">
|
||||
|
||||
|
Before Width: | Height: | Size: 43 KiB After Width: | Height: | Size: 43 KiB |
@ -1,25 +1,18 @@
|
||||
<style>
|
||||
.md-content .md-typeset h1 { display: none; }
|
||||
</style>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://sqlmodel.tiangolo.com"><img src="https://sqlmodel.tiangolo.com/img/logo-margin/logo-margin-vector.svg#only-light" alt="SQLModel"></a>
|
||||
<!-- only-mkdocs -->
|
||||
<a href="https://sqlmodel.tiangolo.com"><img src="img/logo-margin/logo-margin-white-vector.svg#only-dark" alt="SQLModel"></a>
|
||||
<!-- /only-mkdocs -->
|
||||
<a href="https://sqlmodel.tiangolo.com"><img src="https://sqlmodel.tiangolo.com/img/logo-margin/logo-margin-vector.svg" alt="SQLModel"></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
<em>SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness.</em>
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://github.com/fastapi/sqlmodel/actions?query=workflow%3ATest" target="_blank">
|
||||
<img src="https://github.com/fastapi/sqlmodel/workflows/Test/badge.svg" alt="Test">
|
||||
<a href="https://github.com/tiangolo/sqlmodel/actions?query=workflow%3ATest" target="_blank">
|
||||
<img src="https://github.com/tiangolo/sqlmodel/workflows/Test/badge.svg" alt="Test">
|
||||
</a>
|
||||
<a href="https://github.com/fastapi/sqlmodel/actions?query=workflow%3APublish" target="_blank">
|
||||
<img src="https://github.com/fastapi/sqlmodel/workflows/Publish/badge.svg" alt="Publish">
|
||||
<a href="https://github.com/tiangolo/sqlmodel/actions?query=workflow%3APublish" target="_blank">
|
||||
<img src="https://github.com/tiangolo/sqlmodel/workflows/Publish/badge.svg" alt="Publish">
|
||||
</a>
|
||||
<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/sqlmodel" target="_blank">
|
||||
<img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/sqlmodel.svg" alt="Coverage">
|
||||
<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/sqlmodel" target="_blank">
|
||||
<img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/sqlmodel.svg" alt="Coverage">
|
||||
<a href="https://pypi.org/project/sqlmodel" target="_blank">
|
||||
<img src="https://img.shields.io/pypi/v/sqlmodel?color=%2334D058&label=pypi%20package" alt="Package version">
|
||||
</a>
|
||||
@ -29,7 +22,7 @@
|
||||
|
||||
**Documentation**: <a href="https://sqlmodel.tiangolo.com" target="_blank">https://sqlmodel.tiangolo.com</a>
|
||||
|
||||
**Source Code**: <a href="https://github.com/fastapi/sqlmodel" target="_blank">https://github.com/fastapi/sqlmodel</a>
|
||||
**Source Code**: <a href="https://github.com/tiangolo/sqlmodel" target="_blank">https://github.com/tiangolo/sqlmodel</a>
|
||||
|
||||
---
|
||||
|
||||
@ -45,21 +38,6 @@ The key features are:
|
||||
* **Extensible**: You have all the power of SQLAlchemy and Pydantic underneath.
|
||||
* **Short**: Minimize code duplication. A single type annotation does a lot of work. No need to duplicate models in SQLAlchemy and Pydantic.
|
||||
|
||||
## Sponsors
|
||||
|
||||
<!-- sponsors -->
|
||||
|
||||
{% if sponsors %}
|
||||
{% for sponsor in sponsors.gold -%}
|
||||
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
|
||||
{% endfor -%}
|
||||
{%- for sponsor in sponsors.silver -%}
|
||||
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
|
||||
<!-- /sponsors -->
|
||||
|
||||
## SQL Databases in FastAPI
|
||||
|
||||
<a href="https://fastapi.tiangolo.com" target="_blank"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" style="width: 20%;"></a>
|
||||
@ -78,8 +56,6 @@ As **SQLModel** is based on **Pydantic** and **SQLAlchemy**, it requires them. T
|
||||
|
||||
## Installation
|
||||
|
||||
Make sure you create a <a href="https://sqlmodel.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a>, activate it, and then install SQLModel, for example with:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
@ -235,4 +211,4 @@ And at the same time, ✨ it is also a **Pydantic** model ✨. You can use inher
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the terms of the [MIT license](https://github.com/fastapi/sqlmodel/blob/main/LICENSE).
|
||||
This project is licensed under the terms of the [MIT license](https://github.com/tiangolo/sqlmodel/blob/main/LICENSE).
|
||||
|
||||
@ -1,39 +0,0 @@
|
||||
# Install **SQLModel**
|
||||
|
||||
Create a project directory, create a [virtual environment](virtual-environments.md){.internal-link target=_blank}, activate it, and then install **SQLModel**, for example with:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install sqlmodel
|
||||
---> 100%
|
||||
Successfully installed sqlmodel pydantic sqlalchemy
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
As **SQLModel** is built on top of <a href="https://www.sqlalchemy.org/" class="external-link" target="_blank">SQLAlchemy</a> and <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>, when you install `sqlmodel` they will also be automatically installed.
|
||||
|
||||
## Install DB Browser for SQLite
|
||||
|
||||
Remember that [SQLite is a simple database in a single file](databases.md#a-single-file-database){.internal-link target=_blank}?
|
||||
|
||||
For most of the tutorial I'll use SQLite for the examples.
|
||||
|
||||
Python has integrated support for SQLite, it is a single file read and processed from Python. And it doesn't need an [External Database Server](databases.md#a-server-database){.internal-link target=_blank}, so it will be perfect for learning.
|
||||
|
||||
In fact, SQLite is perfectly capable of handling quite big applications. At some point you might want to migrate to a server-based database like <a href="https://www.postgresql.org/" class="external-link" target="_blank">PostgreSQL</a> (which is also free). But for now we'll stick to SQLite.
|
||||
|
||||
Through the tutorial I will show you SQL fragments, and Python examples. And I hope (and expect 🧐) you to actually run them, and verify that the database is working as expected and showing you the same data.
|
||||
|
||||
To be able to explore the SQLite file yourself, independent of Python code (and probably at the same time), I recommend you use <a href="https://sqlitebrowser.org/" class="external-link" target="_blank">DB Browser for SQLite</a>.
|
||||
|
||||
It's a great and simple program to interact with SQLite databases (SQLite files) in a nice user interface.
|
||||
|
||||
<img src="https://sqlitebrowser.org/images/screenshot.png">
|
||||
|
||||
Go ahead and <a href="https://sqlitebrowser.org/" class="external-link" target="_blank">Install DB Browser for SQLite</a>, it's free.
|
||||
|
||||
## Next Steps
|
||||
|
||||
Okay, let's get going! On the next section we'll start the [Tutorial - User Guide](tutorial/index.md). 🚀
|
||||
@ -13,7 +13,7 @@ function setupTermynal() {
|
||||
|
||||
function createTermynals() {
|
||||
document
|
||||
.querySelectorAll(`.${termynalActivateClass} .highlight code`)
|
||||
.querySelectorAll(`.${termynalActivateClass} .highlight`)
|
||||
.forEach(node => {
|
||||
const text = node.textContent;
|
||||
const lines = text.split("\n");
|
||||
@ -110,6 +110,4 @@ async function main() {
|
||||
setupTermynal()
|
||||
}
|
||||
|
||||
document$.subscribe(() => {
|
||||
main()
|
||||
})
|
||||
main()
|
||||
|
||||
@ -1,7 +0,0 @@
|
||||
# Learn
|
||||
|
||||
Learn how to use **SQLModel** here.
|
||||
|
||||
This includes an introduction to **databases**, **SQL**, how to interact with databases from **code** and more.
|
||||
|
||||
You could consider this a **book**, a **course**, the **official** and recommended way to learn **SQLModel**. 😎
|
||||
@ -1,115 +0,0 @@
|
||||
# Repository Management Tasks
|
||||
|
||||
These are the tasks that can be performed to manage the SQLModel repository by [team members](./management.md#team){.internal-link target=_blank}.
|
||||
|
||||
/// tip
|
||||
|
||||
This section is useful only to a handful of people, team members with permissions to manage the repository. You can probably skip it. 😉
|
||||
|
||||
///
|
||||
|
||||
...so, you are a [team member of SQLModel](./management.md#team){.internal-link target=_blank}? Wow, you are so cool! 😎
|
||||
|
||||
You can help with everything on [Help SQLModel - Get Help](./help.md){.internal-link target=_blank} the same ways as external contributors. But additionally, there are some tasks that only you (as part of the team) can perform.
|
||||
|
||||
Here are the general instructions for the tasks you can perform.
|
||||
|
||||
Thanks a lot for your help. 🙇
|
||||
|
||||
## Be Nice
|
||||
|
||||
First of all, be nice. 😊
|
||||
|
||||
You probably are super nice if you were added to the team, but it's worth mentioning it. 🤓
|
||||
|
||||
### When Things are Difficult
|
||||
|
||||
When things are great, everything is easier, so that doesn't need much instructions. But when things are difficult, here are some guidelines.
|
||||
|
||||
Try to find the good side. In general, if people are not being unfriendly, try to thank their effort and interest, even if you disagree with the main subject (discussion, PR), just thank them for being interested in the project, or for having dedicated some time to try to do something.
|
||||
|
||||
It's difficult to convey emotion in text, use emojis to help. 😅
|
||||
|
||||
In discussions and PRs, in many cases, people bring their frustration and show it without filter, in many cases exaggerating, complaining, being entitled, etc. That's really not nice, and when it happens, it lowers our priority to solve their problems. But still, try to breath, and be gentle with your answers.
|
||||
|
||||
Try to avoid using bitter sarcasm or potentially passive-aggressive comments. If something is wrong, it's better to be direct (try to be gentle) than sarcastic.
|
||||
|
||||
Try to be as specific and objective as possible, avoid generalizations.
|
||||
|
||||
For conversations that are more difficult, for example to reject a PR, you can ask me (@tiangolo) to handle it directly.
|
||||
|
||||
## Edit PR Titles
|
||||
|
||||
* Edit the PR title to start with an emoji from <a href="https://gitmoji.dev/" class="external-link" target="_blank">gitmoji</a>.
|
||||
* Use the emoji character, not the GitHub code. So, use `🐛` instead of `:bug:`. This is so that it shows up correctly outside of GitHub, for example in the release notes.
|
||||
* Start the title with a verb. For example `Add`, `Refactor`, `Fix`, etc. This way the title will say the action that the PR does. Like `Add support for teleporting`, instead of `Teleporting wasn't working, so this PR fixes it`.
|
||||
* Edit the text of the PR title to start in "imperative", like giving an order. So, instead of `Adding support for teleporting` use `Add support for teleporting`.
|
||||
* Try to make the title descriptive about what it achieves. If it's a feature, try to describe it, for example `Add support for teleporting` instead of `Create TeleportAdapter class`.
|
||||
* Do not finish the title with a period (`.`).
|
||||
|
||||
Once the PR is merged, a GitHub Action (<a href="https://github.com/tiangolo/latest-changes" class="external-link" target="_blank">latest-changes</a>) will use the PR title to update the latest changes automatically.
|
||||
|
||||
So, having a nice PR title will not only look nice in GitHub, but also in the release notes. 📝
|
||||
|
||||
## Add Labels to PRs
|
||||
|
||||
The same GitHub Action <a href="https://github.com/tiangolo/latest-changes" class="external-link" target="_blank">latest-changes</a> uses one label in the PR to decide the section in the release notes to put this PR in.
|
||||
|
||||
Make sure you use a supported label from the <a href="https://github.com/tiangolo/latest-changes#using-labels" class="external-link" target="_blank">latest-changes list of labels</a>:
|
||||
|
||||
* `breaking`: Breaking Changes
|
||||
* Existing code will break if they update the version without changing their code. This rarely happens, so this label is not frequently used.
|
||||
* `security`: Security Fixes
|
||||
* This is for security fixes, like vulnerabilities. It would almost never be used.
|
||||
* `feature`: Features
|
||||
* New features, adding support for things that didn't exist before.
|
||||
* `bug`: Fixes
|
||||
* Something that was supported didn't work, and this fixes it. There are many PRs that claim to be bug fixes because the user is doing something in an unexpected way that is not supported, but they considered it what should be supported by default. Many of these are actually features or refactors. But in some cases there's an actual bug.
|
||||
* `refactor`: Refactors
|
||||
* This is normally for changes to the internal code that don't change the behavior. Normally it improves maintainability, or enables future features, etc.
|
||||
* `upgrade`: Upgrades
|
||||
* This is for upgrades to direct dependencies from the project, or extra optional dependencies, normally in `pyproject.toml`. So, things that would affect final users, they would end up receiving the upgrade in their code base once they update. But this is not for upgrades to internal dependencies used for development, testing, docs, etc. Those internal dependencies, normally in `requirements.txt` files or GitHub Action versions should be marked as `internal`, not `upgrade`.
|
||||
* `docs`: Docs
|
||||
* Changes in docs. This includes updating the docs, fixing typos. But it doesn't include changes to translations.
|
||||
* You can normally quickly detect it by going to the "Files changed" tab in the PR and checking if the updated file(s) starts with `docs/en/docs`. The original version of the docs is always in English, so in `docs/en/docs`.
|
||||
* `internal`: Internal
|
||||
* Use this for changes that only affect how the repo is managed. For example upgrades to internal dependencies, changes in GitHub Actions or scripts, etc.
|
||||
|
||||
/// tip
|
||||
|
||||
Some tools like Dependabot, will add some labels, like `dependencies`, but have in mind that this label is not used by the `latest-changes` GitHub Action, so it won't be used in the release notes. Please make sure one of the labels above is added.
|
||||
|
||||
///
|
||||
|
||||
## Review PRs
|
||||
|
||||
If a PR doesn't explain what it does or why, ask for more information.
|
||||
|
||||
A PR should have a specific use case that it is solving.
|
||||
|
||||
* If the PR is for a feature, it should have docs.
|
||||
* Unless it's a feature we want to discourage, like support for a corner case that we don't want users to use.
|
||||
* The docs should include a source example file, not write Python directly in Markdown.
|
||||
* If the source example(s) file can have different syntax for Python 3.8, 3.9, 3.10, there should be different versions of the file, and they should be shown in tabs in the docs.
|
||||
* There should be tests testing the source example.
|
||||
* Before the PR is applied, the new tests should fail.
|
||||
* After applying the PR, the new tests should pass.
|
||||
* Coverage should stay at 100%.
|
||||
* If you see the PR makes sense, or we discussed it and considered it should be accepted, you can add commits on top of the PR to tweak it, to add docs, tests, format, refactor, remove extra files, etc.
|
||||
* Feel free to comment in the PR to ask for more information, to suggest changes, etc.
|
||||
* Once you think the PR is ready, move it in the internal GitHub project for me to review it.
|
||||
|
||||
## Dependabot PRs
|
||||
|
||||
Dependabot will create PRs to update dependencies for several things, and those PRs all look similar, but some are way more delicate than others.
|
||||
|
||||
* If the PR is for a direct dependency, so, Dependabot is modifying `pyproject.toml`, **don't merge it**. 😱 Let me check it first. There's a good chance that some additional tweaks or updates are needed.
|
||||
* If the PR updates one of the internal dependencies, for example it's modifying `requirements.txt` files, or GitHub Action versions, if the tests are passing, the release notes (shown in a summary in the PR) don't show any obvious potential breaking change, you can merge it. 😎
|
||||
|
||||
## Mark GitHub Discussions Answers
|
||||
|
||||
When a question in GitHub Discussions has been answered, mark the answer by clicking "Mark as answer".
|
||||
|
||||
Many of the current Discussion Questions were migrated from old issues. Many have the label `answered`, that means they were answered when they were issues, but now in GitHub Discussions, it's not known what is the actual response from the messages.
|
||||
|
||||
You can filter discussions by <a href="https://github.com/fastapi/sqlmodel/discussions/categories/questions?discussions_q=category:Questions+is:open+is:unanswered" class="external-link" target="_blank">`Questions` that are `Unanswered`</a>.
|
||||
@ -1,45 +0,0 @@
|
||||
# Repository Management
|
||||
|
||||
Here's a short description of how the SQLModel repository is managed and maintained.
|
||||
|
||||
## Owner
|
||||
|
||||
I, <a href="https://github.com/tiangolo" target="_blank">@tiangolo</a>, am the creator and owner of the SQLModel repository. 🤓
|
||||
|
||||
I normally give the final review to each PR before merging them. I make the final decisions on the project, I'm the <a href="https://en.wikipedia.org/wiki/Benevolent_dictator_for_life" class="external-link" target="_blank"><abbr title="Benevolent Dictator For Life">BDFL</abbr></a>. 😅
|
||||
|
||||
## Team
|
||||
|
||||
There's a team of people that help manage and maintain the project. 😎
|
||||
|
||||
They have different levels of permissions and [specific instructions](./management-tasks.md){.internal-link target=_blank}.
|
||||
|
||||
Some of the tasks they can perform include:
|
||||
|
||||
* Adding labels to PRs.
|
||||
* Editing PR titles.
|
||||
* Adding commits on top of PRs to tweak them.
|
||||
* Mark answers in GitHub Discussions questions, etc.
|
||||
* Merge some specific types of PRs.
|
||||
|
||||
Joining the team is by invitation only, and I could update or remove permissions, instructions, or membership.
|
||||
|
||||
### Team Members
|
||||
|
||||
This is the current list of team members. 😎
|
||||
|
||||
<div class="user-list user-list-center">
|
||||
{% for user in members["members"] %}
|
||||
|
||||
<div class="user"><a href="https://github.com/{{ user.login }}" target="_blank"><div class="avatar-wrapper"><img src="https://github.com/{{ user.login }}.png"/></div><div class="title">@{{ user.login }}</div></a></div>
|
||||
{% endfor %}
|
||||
|
||||
</div>
|
||||
|
||||
Additional to them, there's a large community of people helping each other and getting involved in the projects in different ways.
|
||||
|
||||
## External Contributions
|
||||
|
||||
External contributions are very welcome and appreciated, including answering questions, submitting PRs, etc. 🙇♂️
|
||||
|
||||
There are many ways to [help maintain SQLModel](./help.md){.internal-link target=_blank}.
|
||||
@ -1 +1,31 @@
|
||||
{% extends "base.html" %}
|
||||
{%- block scripts %}
|
||||
{{ super() }}
|
||||
<script src="https://cdn.jsdelivr.net/npm/qabot@0.4"></script>
|
||||
<script>
|
||||
// This prevents the global search from interfering with qa-bot's internal text input.
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
document.querySelectorAll('qa-bot').forEach((x) => {
|
||||
x.addEventListener('keydown', (event) => {
|
||||
event.stopPropagation();
|
||||
});
|
||||
});
|
||||
});
|
||||
</script>
|
||||
<qa-bot
|
||||
server="https://tiangolo-sqlmodel.docsqa.jina.ai"
|
||||
theme="infer"
|
||||
title="SQLModel Bot"
|
||||
description="SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness."
|
||||
style="font-size: 0.8rem"
|
||||
>
|
||||
<template>
|
||||
<dl>
|
||||
<dt>You can ask questions about SQLModel. Try:</dt>
|
||||
<dd>Which Python version is supported?</dd>
|
||||
<dd>How SQLModel interacts with the database?</dd>
|
||||
<dd>How can I link tables?</dd>
|
||||
</dl>
|
||||
</template>
|
||||
</qa-bot>
|
||||
{%- endblock %}
|
||||
|
||||
@ -2,268 +2,8 @@
|
||||
|
||||
## Latest Changes
|
||||
|
||||
### Refactors
|
||||
|
||||
* 🚨 Fix types for new Pydantic. PR [#1131](https://github.com/fastapi/sqlmodel/pull/1131) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
### Docs
|
||||
|
||||
* ✏️ Fix typo in the release notes of v0.0.22. PR [#1195](https://github.com/fastapi/sqlmodel/pull/1195) by [@PipeKnight](https://github.com/PipeKnight).
|
||||
* 📝 Update includes for `docs/advanced/uuid.md`. PR [#1151](https://github.com/fastapi/sqlmodel/pull/1151) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 📝 Update includes for `docs/tutorial/create-db-and-table.md`. PR [#1149](https://github.com/fastapi/sqlmodel/pull/1149) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 📝 Fix internal links in docs. PR [#1148](https://github.com/fastapi/sqlmodel/pull/1148) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ✏️ Fix typo in documentation. PR [#1106](https://github.com/fastapi/sqlmodel/pull/1106) by [@Solipsistmonkey](https://github.com/Solipsistmonkey).
|
||||
* 📝 Remove highlights in `indexes.md` . PR [#1100](https://github.com/fastapi/sqlmodel/pull/1100) by [@alejsdev](https://github.com/alejsdev).
|
||||
|
||||
### Internal
|
||||
|
||||
* ⬆️ Upgrade markdown-include-variants to version 0.0.3. PR [#1152](https://github.com/fastapi/sqlmodel/pull/1152) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Update issue manager workflow. PR [#1137](https://github.com/fastapi/sqlmodel/pull/1137) by [@alejsdev](https://github.com/alejsdev).
|
||||
* 👷 Fix smokeshow, checkout files on CI. PR [#1136](https://github.com/fastapi/sqlmodel/pull/1136) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Use uv in CI. PR [#1135](https://github.com/fastapi/sqlmodel/pull/1135) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ➕ Add docs dependency markdown-include-variants. PR [#1129](https://github.com/fastapi/sqlmodel/pull/1129) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔨 Update script to standardize format. PR [#1130](https://github.com/fastapi/sqlmodel/pull/1130) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Update `labeler.yml`. PR [#1128](https://github.com/fastapi/sqlmodel/pull/1128) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Update worfkow deploy-docs-notify URL. PR [#1126](https://github.com/fastapi/sqlmodel/pull/1126) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Upgrade Cloudflare GitHub Action. PR [#1124](https://github.com/fastapi/sqlmodel/pull/1124) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#1097](https://github.com/fastapi/sqlmodel/pull/1097) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
|
||||
* ⬆ Bump tiangolo/issue-manager from 0.5.0 to 0.5.1. PR [#1107](https://github.com/fastapi/sqlmodel/pull/1107) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
* 👷 Update `issue-manager.yml`. PR [#1103](https://github.com/fastapi/sqlmodel/pull/1103) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Fix coverage processing in CI, one name per matrix run. PR [#1104](https://github.com/fastapi/sqlmodel/pull/1104) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 💚 Set `include-hidden-files` to `True` when using the `upload-artifact` GH action. PR [#1098](https://github.com/fastapi/sqlmodel/pull/1098) by [@svlandeg](https://github.com/svlandeg).
|
||||
* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#1088](https://github.com/fastapi/sqlmodel/pull/1088) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
|
||||
|
||||
## 0.0.22
|
||||
|
||||
### Fixes
|
||||
|
||||
* 🐛 Fix support for types with `Optional[Annotated[x, f()]]`, e.g. `id: Optional[pydantic.UUID4]`. PR [#1093](https://github.com/fastapi/sqlmodel/pull/1093) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
### Docs
|
||||
|
||||
* ✏️ Fix a typo in `docs/virtual-environments.md`. PR [#1085](https://github.com/fastapi/sqlmodel/pull/1085) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 📝 Add docs for virtual environments and environment variables, update contributing. PR [#1082](https://github.com/fastapi/sqlmodel/pull/1082) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 📝 Add docs about repo management and team. PR [#1059](https://github.com/tiangolo/sqlmodel/pull/1059) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ✏️ Fix typo in `cascade_delete` docs. PR [#1030](https://github.com/tiangolo/sqlmodel/pull/1030) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
### Internal
|
||||
|
||||
* ✅ Refactor test_enums to make them independent of previous imports. PR [#1095](https://github.com/fastapi/sqlmodel/pull/1095) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Update `latest-changes` GitHub Action. PR [#1087](https://github.com/fastapi/sqlmodel/pull/1087) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#1028](https://github.com/fastapi/sqlmodel/pull/1028) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
|
||||
* ⬆ Bump ruff from 0.4.7 to 0.6.2. PR [#1081](https://github.com/fastapi/sqlmodel/pull/1081) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
* 🔧 Update lint script. PR [#1084](https://github.com/fastapi/sqlmodel/pull/1084) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Update Python version for coverage. PR [#1083](https://github.com/fastapi/sqlmodel/pull/1083) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Update coverage config files. PR [#1077](https://github.com/fastapi/sqlmodel/pull/1077) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Add URLs to `pyproject.toml`, show up in PyPI. PR [#1074](https://github.com/fastapi/sqlmodel/pull/1074) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Do not sync labels as it overrides manually added labels. PR [#1073](https://github.com/fastapi/sqlmodel/pull/1073) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Update configs for GitHub Action labeler, to add only one label. PR [#1072](https://github.com/fastapi/sqlmodel/pull/1072) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Update labeler GitHub Actions permissions and dependencies. PR [#1071](https://github.com/fastapi/sqlmodel/pull/1071) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Add GitHub Action label-checker. PR [#1069](https://github.com/fastapi/sqlmodel/pull/1069) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Add GitHub Action labeler. PR [#1068](https://github.com/fastapi/sqlmodel/pull/1068) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Update GitHub Action add-to-project. PR [#1067](https://github.com/fastapi/sqlmodel/pull/1067) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Add GitHub Action add-to-project. PR [#1066](https://github.com/fastapi/sqlmodel/pull/1066) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 📝 Update admonitions in annotations. PR [#1065](https://github.com/fastapi/sqlmodel/pull/1065) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 📝 Update links from github.com/tiangolo/sqlmodel to github.com/fastapi/sqlmodel. PR [#1064](https://github.com/fastapi/sqlmodel/pull/1064) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Update members. PR [#1063](https://github.com/tiangolo/sqlmodel/pull/1063) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 💄 Add dark-mode logo. PR [#1061](https://github.com/tiangolo/sqlmodel/pull/1061) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔨 Update docs.py script to enable dirty reload conditionally. PR [#1060](https://github.com/tiangolo/sqlmodel/pull/1060) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Update MkDocs previews. PR [#1058](https://github.com/tiangolo/sqlmodel/pull/1058) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 💄 Update Termynal line-height. PR [#1057](https://github.com/tiangolo/sqlmodel/pull/1057) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Upgrade build docs configs. PR [#1047](https://github.com/tiangolo/sqlmodel/pull/1047) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Add alls-green for test-redistribute. PR [#1055](https://github.com/tiangolo/sqlmodel/pull/1055) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Update docs-previews to handle no docs changes. PR [#1056](https://github.com/tiangolo/sqlmodel/pull/1056) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷🏻 Show docs deployment status and preview URLs in comment. PR [#1054](https://github.com/tiangolo/sqlmodel/pull/1054) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Enable auto dark mode. PR [#1046](https://github.com/tiangolo/sqlmodel/pull/1046) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Update issue-manager. PR [#1045](https://github.com/tiangolo/sqlmodel/pull/1045) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Update issue-manager.yml GitHub Action permissions. PR [#1040](https://github.com/tiangolo/sqlmodel/pull/1040) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ♻️ Refactor Deploy Docs GitHub Action to be a script and update token preparing for org. PR [#1039](https://github.com/tiangolo/sqlmodel/pull/1039) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.0.21
|
||||
|
||||
### Features
|
||||
|
||||
* ✨ Add support for cascade delete relationships: `cascade_delete`, `ondelete`, and `passive_deletes`. Initial PR [#983](https://github.com/tiangolo/sqlmodel/pull/983) by [@estebanx64](https://github.com/estebanx64).
|
||||
* New docs at: [Cascade Delete Relationships](https://sqlmodel.tiangolo.com/tutorial/relationship-attributes/cascade-delete-relationships/).
|
||||
|
||||
### Docs
|
||||
|
||||
* 📝 Update docs . PR [#1003](https://github.com/tiangolo/sqlmodel/pull/1003) by [@alejsdev](https://github.com/alejsdev).
|
||||
|
||||
### Internal
|
||||
|
||||
* ⬆ Bump actions/cache from 3 to 4. PR [#783](https://github.com/tiangolo/sqlmodel/pull/783) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
* ⬆ Bump cairosvg from 2.7.0 to 2.7.1. PR [#919](https://github.com/tiangolo/sqlmodel/pull/919) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
* ⬆ Bump jinja2 from 3.1.3 to 3.1.4. PR [#974](https://github.com/tiangolo/sqlmodel/pull/974) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
* ⬆ Bump pypa/gh-action-pypi-publish from 1.8.11 to 1.9.0. PR [#987](https://github.com/tiangolo/sqlmodel/pull/987) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
* ⬆ Bump mkdocstrings[python] from 0.23.0 to 0.25.1. PR [#927](https://github.com/tiangolo/sqlmodel/pull/927) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
* ⬆ Bump dorny/paths-filter from 2 to 3. PR [#972](https://github.com/tiangolo/sqlmodel/pull/972) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
|
||||
## 0.0.20
|
||||
|
||||
### Features
|
||||
|
||||
* ✨ Add official UUID support, docs and tests, internally using new SQLAlchemy 2.0 types. Initial PR [#992](https://github.com/tiangolo/sqlmodel/pull/992) by [@estebanx64](https://github.com/estebanx64).
|
||||
* New docs in the [Advanced User Guide: UUID (Universally Unique Identifiers)](https://sqlmodel.tiangolo.com/advanced/uuid/).
|
||||
|
||||
### Docs
|
||||
|
||||
* ✏️ Fix internal link in `docs/tutorial/create-db-and-table.md`. PR [#911](https://github.com/tiangolo/sqlmodel/pull/911) by [@tfpgh](https://github.com/tfpgh).
|
||||
* ✏️ Add missing step in `create-db-and-table-with-db-browser.md`. PR [#976](https://github.com/tiangolo/sqlmodel/pull/976) by [@alejsdev](https://github.com/alejsdev).
|
||||
* ✏️ Fix typo in `docs/tutorial`. PR [#943](https://github.com/tiangolo/sqlmodel/pull/943) by [@luco17](https://github.com/luco17).
|
||||
* ✏️ Fix typo in `sqlmodel/_compat.py`. PR [#950](https://github.com/tiangolo/sqlmodel/pull/950) by [@Highfire1](https://github.com/Highfire1).
|
||||
* ✏️ Update pip installation command in tutorial. PR [#975](https://github.com/tiangolo/sqlmodel/pull/975) by [@alejsdev](https://github.com/alejsdev).
|
||||
* ✏️ Fix typo in `docs/tutorial/relationship-attributes/index.md`. PR [#880](https://github.com/tiangolo/sqlmodel/pull/880) by [@UncleGoogle](https://github.com/UncleGoogle).
|
||||
|
||||
### Internal
|
||||
|
||||
* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#979](https://github.com/tiangolo/sqlmodel/pull/979) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
|
||||
* 🔨 Update docs Termynal scripts to not include line nums for local dev. PR [#1018](https://github.com/tiangolo/sqlmodel/pull/1018) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.0.19
|
||||
|
||||
### Fixes
|
||||
|
||||
* 🐛 Fix pydantic `EmailStr` support and `max_length` in several String subclasses. PR [#966](https://github.com/tiangolo/sqlmodel/pull/966) by [@estebanx64](https://github.com/estebanx64).
|
||||
* 🐛 Fix set varchar limit when `max_length` is set on Pydantic models using Pydantic v2. PR [#963](https://github.com/tiangolo/sqlmodel/pull/963) by [@estebanx64](https://github.com/estebanx64).
|
||||
|
||||
### Refactors
|
||||
|
||||
* ♻️ Refactor generate select template to isolate templated code to the minimum. PR [#967](https://github.com/tiangolo/sqlmodel/pull/967) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
### Upgrades
|
||||
|
||||
* ⬆️ Update minimum SQLAlchemy version to 2.0.14 as that one includes `TryCast` used internally. PR [#964](https://github.com/tiangolo/sqlmodel/pull/964) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
### Docs
|
||||
|
||||
* ✏️ Fix broken link to `@dataclass_transform` (now PEP 681) in `docs/features.md`. PR [#753](https://github.com/tiangolo/sqlmodel/pull/753) by [@soof-golan](https://github.com/soof-golan).
|
||||
|
||||
### Internal
|
||||
|
||||
* ⬆️ Upgrade Ruff and Black. PR [#968](https://github.com/tiangolo/sqlmodel/pull/968) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ⬆ Bump tiangolo/issue-manager from 0.4.1 to 0.5.0. PR [#922](https://github.com/tiangolo/sqlmodel/pull/922) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
* 📌 Pin typing-extensions in tests for compatiblity with Python 3.8, dirty-equals, Pydantic. PR [#965](https://github.com/tiangolo/sqlmodel/pull/965) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Update GitHub Actions to download and upload artifacts. PR [#936](https://github.com/tiangolo/sqlmodel/pull/936) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Tweak CI for test-redistribute, add needed env vars for slim. PR [#929](https://github.com/tiangolo/sqlmodel/pull/929) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.0.18
|
||||
|
||||
### Internal
|
||||
|
||||
* ✨ Add `sqlmodel-slim` setup. PR [#916](https://github.com/tiangolo/sqlmodel/pull/916) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
In the future SQLModel will include the standard default recommended packages, and `sqlmodel-slim` will come without those recommended standard packages and with a group of optional dependencies `sqlmodel-slim[standard]`, equivalent to `sqlmodel`, for those that want to opt out of those packages.
|
||||
|
||||
* 🔧 Re-enable MkDocs Material Social plugin. PR [#915](https://github.com/tiangolo/sqlmodel/pull/915) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.0.17
|
||||
|
||||
### Refactors
|
||||
|
||||
* ♻️ Refactor types to properly support Pydantic 2.7. PR [#913](https://github.com/tiangolo/sqlmodel/pull/913) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
### Docs
|
||||
|
||||
* 📝 Update ModelRead to ModelPublic documentation and examples. PR [#885](https://github.com/tiangolo/sqlmodel/pull/885) by [@estebanx64](https://github.com/estebanx64).
|
||||
* ✨ Add source examples for Python 3.10 and 3.9 with updated syntax. PR [#842](https://github.com/tiangolo/sqlmodel/pull/842) by [@tiangolo](https://github.com/tiangolo) and [@estebanx64](https://github.com/estebanx64).
|
||||
|
||||
### Internal
|
||||
|
||||
* ⬆ Bump actions/setup-python from 4 to 5. PR [#733](https://github.com/tiangolo/sqlmodel/pull/733) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
* 🔨 Update internal scripts and remove unused ones. PR [#914](https://github.com/tiangolo/sqlmodel/pull/914) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Migrate from Poetry to PDM for the internal build config. PR [#912](https://github.com/tiangolo/sqlmodel/pull/912) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Update MkDocs, disable cards while I can upgrade to the latest MkDocs Material, that fixes an issue with social cards. PR [#888](https://github.com/tiangolo/sqlmodel/pull/888) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 👷 Add cron to run test once a week on monday. PR [#869](https://github.com/tiangolo/sqlmodel/pull/869) by [@estebanx64](https://github.com/estebanx64).
|
||||
* ⬆️ Upgrade Ruff version and configs. PR [#859](https://github.com/tiangolo/sqlmodel/pull/859) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔥 Remove Jina QA Bot as it has been discontinued. PR [#840](https://github.com/tiangolo/sqlmodel/pull/840) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.0.16
|
||||
|
||||
### Features
|
||||
|
||||
* ✨ Add new method `.sqlmodel_update()` to update models in place, including an `update` parameter for extra data. And fix implementation for the (now documented) `update` parameter for `.model_validate()`. PR [#804](https://github.com/tiangolo/sqlmodel/pull/804) by [@tiangolo](https://github.com/tiangolo).
|
||||
* Updated docs: [Update Data with FastAPI](https://sqlmodel.tiangolo.com/tutorial/fastapi/update/).
|
||||
* New docs: [Update with Extra Data (Hashed Passwords) with FastAPI](https://sqlmodel.tiangolo.com/tutorial/fastapi/update-extra-data/).
|
||||
|
||||
## 0.0.15
|
||||
|
||||
### Fixes
|
||||
|
||||
* 🐛 Fix class initialization compatibility with Pydantic and SQLModel, fixing errors revealed by the latest Pydantic. PR [#807](https://github.com/tiangolo/sqlmodel/pull/807) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
### Internal
|
||||
|
||||
* ⬆ Bump tiangolo/issue-manager from 0.4.0 to 0.4.1. PR [#775](https://github.com/tiangolo/sqlmodel/pull/775) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
* 👷 Fix GitHub Actions build docs filter paths for GitHub workflows. PR [#738](https://github.com/tiangolo/sqlmodel/pull/738) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.0.14
|
||||
|
||||
### Features
|
||||
|
||||
* ✨ Add support for Pydantic v2 (while keeping support for v1 if v2 is not available). PR [#722](https://github.com/tiangolo/sqlmodel/pull/722) by [@tiangolo](https://github.com/tiangolo) including initial work in PR [#699](https://github.com/tiangolo/sqlmodel/pull/699) by [@AntonDeMeester](https://github.com/AntonDeMeester).
|
||||
|
||||
## 0.0.13
|
||||
|
||||
### Fixes
|
||||
|
||||
* ♻️ Refactor type generation of selects re-order to prioritize models to optimize editor support. PR [#718](https://github.com/tiangolo/sqlmodel/pull/718) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
### Refactors
|
||||
|
||||
* 🔇 Do not raise deprecation warnings for execute as it's automatically used internally. PR [#716](https://github.com/tiangolo/sqlmodel/pull/716) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ✅ Move OpenAPI tests inline to simplify updating them with Pydantic v2. PR [#709](https://github.com/tiangolo/sqlmodel/pull/709) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
### Upgrades
|
||||
|
||||
* ⬆️ Add support for Python 3.11 and Python 3.12. PR [#710](https://github.com/tiangolo/sqlmodel/pull/710) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
### Docs
|
||||
|
||||
* ✏️ Fix typo, simplify single quote/apostrophe character in "Sister Margaret's" everywhere in the docs. PR [#721](https://github.com/tiangolo/sqlmodel/pull/721) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 📝 Update docs for Decimal, use proper types. PR [#719](https://github.com/tiangolo/sqlmodel/pull/719) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 📝 Add source examples for Python 3.9 and 3.10. PR [#715](https://github.com/tiangolo/sqlmodel/pull/715) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
### Internal
|
||||
|
||||
* 🙈 Update gitignore, include all coverage files. PR [#711](https://github.com/tiangolo/sqlmodel/pull/711) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Update config with new pymdown extensions. PR [#712](https://github.com/tiangolo/sqlmodel/pull/712) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 🔧 Update docs build setup, add support for sponsors, add sponsor GOVCERT.LU. PR [#720](https://github.com/tiangolo/sqlmodel/pull/720) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#697](https://github.com/tiangolo/sqlmodel/pull/697) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
|
||||
* 🔧 Show line numbers in docs during local development. PR [#714](https://github.com/tiangolo/sqlmodel/pull/714) by [@tiangolo](https://github.com/tiangolo).
|
||||
* 📝 Update details syntax with new pymdown extensions format. PR [#713](https://github.com/tiangolo/sqlmodel/pull/713) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.0.12
|
||||
|
||||
### Features
|
||||
|
||||
* ✨ Upgrade SQLAlchemy to 2.0. PR [#700](https://github.com/tiangolo/sqlmodel/pull/700) by [@tiangolo](https://github.com/tiangolo) including initial work in PR [#563](https://github.com/tiangolo/sqlmodel/pull/563) by [@farahats9](https://github.com/farahats9).
|
||||
|
||||
### Internal
|
||||
|
||||
* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#686](https://github.com/tiangolo/sqlmodel/pull/686) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
|
||||
* 👷 Upgrade latest-changes GitHub Action. PR [#693](https://github.com/tiangolo/sqlmodel/pull/693) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
## 0.0.11
|
||||
|
||||
### Features
|
||||
|
||||
* ✨ Add support for passing a custom SQLAlchemy type to `Field()` with `sa_type`. PR [#505](https://github.com/tiangolo/sqlmodel/pull/505) by [@maru0123-2004](https://github.com/maru0123-2004).
|
||||
* You might consider this a breaking change if you were using an incompatible combination of arguments, those arguments were not taking effect and now you will have a type error and runtime error telling you that.
|
||||
* ✨ Do not allow invalid combinations of field parameters for columns and relationships, `sa_column` excludes `sa_column_args`, `primary_key`, `nullable`, etc. PR [#681](https://github.com/tiangolo/sqlmodel/pull/681) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
### Docs
|
||||
|
||||
* 🎨 Update inline source examples, hide `#` in annotations (from MkDocs Material). PR [#677](https://github.com/tiangolo/sqlmodel/pull/677) by [@Matthieu-LAURENT39](https://github.com/Matthieu-LAURENT39).
|
||||
|
||||
### Internal
|
||||
|
||||
* ⬆ Update coverage requirement from ^6.2 to >=6.2,<8.0. PR [#663](https://github.com/tiangolo/sqlmodel/pull/663) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
* ⬆ Update mkdocs-material requirement from 9.1.21 to 9.2.7. PR [#675](https://github.com/tiangolo/sqlmodel/pull/675) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
* ⬆️ Upgrade mypy manually. PR [#684](https://github.com/tiangolo/sqlmodel/pull/684) by [@tiangolo](https://github.com/tiangolo).
|
||||
* ⬆ Update black requirement from ^22.10.0 to >=22.10,<24.0. PR [#664](https://github.com/tiangolo/sqlmodel/pull/664) by [@dependabot[bot]](https://github.com/apps/dependabot).
|
||||
* 👷 Update CI to build MkDocs Insiders only when the secrets are available, for Dependabot. PR [#683](https://github.com/tiangolo/sqlmodel/pull/683) by [@tiangolo](https://github.com/tiangolo).
|
||||
|
||||
* ✨ Do not allow invalid combinations of field parameters for columns and relationships, `sa_column` excludes `sa_column_args`, `primary_key`, `nullable`, etc.. PR [#681](https://github.com/tiangolo/sqlmodel/pull/681) by [@tiangolo](https://github.com/tiangolo).
|
||||
## 0.0.10
|
||||
|
||||
### Features
|
||||
|
||||
@ -1,3 +0,0 @@
|
||||
# Resources
|
||||
|
||||
Additional resources, how to **help** and get help, how to **contribute**, and more. ✈️
|
||||
@ -4,21 +4,7 @@ In the previous chapter, we saw how to add rows to the database using **SQLModel
|
||||
|
||||
Now let's talk a bit about why the `id` field **can't be `NULL`** on the database because it's a **primary key**, and we declare it using `Field(primary_key=True)`.
|
||||
|
||||
But the same `id` field actually **can be `None`** in the Python code, so we declare the type with `int | None (or Optional[int])`, and set the default value to `Field(default=None)`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="4"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001_py310.py[ln:4-8]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
But the same `id` field actually **can be `None`** in the Python code, so we declare the type with `Optional[int]`, and set the default value to `Field(default=None)`:
|
||||
|
||||
```Python hl_lines="4"
|
||||
# Code above omitted 👆
|
||||
@ -28,27 +14,14 @@ But the same `id` field actually **can be `None`** in the Python code, so we dec
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Next, I'll show you a bit more about the synchronization of data between the database and the Python code.
|
||||
|
||||
@ -58,20 +31,6 @@ When do we get an actual `int` from the database in that `id` field? Let's see a
|
||||
|
||||
When we create a new `Hero` instance, we don't set the `id`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3-6"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001_py310.py[ln:21-24]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3-6"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -80,27 +39,14 @@ When we create a new `Hero` instance, we don't set the `id`:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
### How `Optional` Helps
|
||||
|
||||
@ -128,20 +74,6 @@ But by declaring it with `Optional[int]`, the editor will help us to avoid writi
|
||||
|
||||
We can confirm that by printing our heroes before adding them to the database:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="9-11"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001_py310.py[ln:21-29]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="9-11"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -150,27 +82,14 @@ We can confirm that by printing our heroes before adding them to the database:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
That will output:
|
||||
|
||||
@ -201,20 +120,6 @@ After we add the `Hero` instance objects to the **session**, the IDs are *still*
|
||||
|
||||
We can verify by creating a session using a `with` block and adding the objects. And then printing them again:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="19-21"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001_py310.py[ln:21-39]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="19-21"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -223,27 +128,14 @@ We can verify by creating a session using a `with` block and adding the objects.
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This will, again, output the `id`s of the objects as `None`:
|
||||
|
||||
@ -268,21 +160,7 @@ As we saw before, the **session** is smart and doesn't talk to the database ever
|
||||
|
||||
Then we can `commit` the changes in the session, and print again:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="13 16-18"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001_py310.py[ln:31-46]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="13 16-18"
|
||||
```Python hl_lines="13 16-18"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py[ln:33-48]!}
|
||||
@ -290,27 +168,14 @@ Then we can `commit` the changes in the session, and print again:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
And now, something unexpected happens, look at the output, it seems as if the `Hero` instance objects had no data at all:
|
||||
|
||||
@ -368,21 +233,7 @@ We didn't access the object's attributes, like `hero.name`. We only accessed the
|
||||
|
||||
To confirm and understand how this **automatic expiration and refresh** of data when accessing attributes work, we can print some individual fields (instance attributes):
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="21-23 26-28"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001_py310.py[ln:31-56]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="21-23 26-28"
|
||||
```Python hl_lines="21-23 26-28"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py[ln:33-58]!}
|
||||
@ -390,27 +241,14 @@ To confirm and understand how this **automatic expiration and refresh** of data
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Now we are actually accessing the attributes, because instead of printing the whole object `hero_1`:
|
||||
|
||||
@ -479,6 +317,7 @@ Hero 2 name: Spider-Boy
|
||||
Hero 3 name: Rusty-Man
|
||||
|
||||
// Because the Session already refreshed these objects with all their data and the session knows they are not expired, it doesn't have to go again to the database for the names 🤓
|
||||
|
||||
```
|
||||
|
||||
</div>
|
||||
@ -491,21 +330,7 @@ But what if you want to **explicitly refresh** the data?
|
||||
|
||||
You can do that too with `session.refresh(object)`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="30-32 35-37"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001_py310.py[ln:31-65]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="30-32 35-37"
|
||||
```Python hl_lines="30-32 35-37"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py[ln:33-67]!}
|
||||
@ -513,27 +338,14 @@ You can do that too with `session.refresh(object)`:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
When Python executes this code:
|
||||
|
||||
@ -591,20 +403,6 @@ Now, as a final experiment, we can also print data after the **session** is clos
|
||||
|
||||
There are no surprises here, it still works:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="40-42"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001_py310.py[ln:31-70]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="40-42"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -613,27 +411,14 @@ There are no surprises here, it still works:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
And the output shows again the same data:
|
||||
|
||||
@ -660,34 +445,17 @@ Hero 3: age=48 id=3 name='Rusty-Man' secret_name='Tommy Sharp'
|
||||
|
||||
Now let's review all this code once again.
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
Each one of the numbered bubbles shows what each line will print in the output.
|
||||
|
||||
Each one of the numbered bubbles shows what each line will print in the output.
|
||||
And as we created the **engine** with `echo=True`, we can see the SQL statements being executed at each step.
|
||||
|
||||
And as we created the **engine** with `echo=True`, we can see the SQL statements being executed at each step.
|
||||
|
||||
///
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/annotations/en/tutorial002.md!}
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python
|
||||
```{ .python .annotate }
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial002.py!}
|
||||
```
|
||||
|
||||
{!./docs_src/tutorial/automatic_id_none_refresh/annotations/en/tutorial002.md!}
|
||||
|
||||
////
|
||||
|
||||
And here's all the output generated by running this program, all together:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
@ -138,7 +138,7 @@ So, the output would be:
|
||||
$ python -m project.app
|
||||
|
||||
Created hero: id=1 secret_name='Dive Wilson' team_id=1 name='Deadpond' age=None
|
||||
Hero's team: name='Z-Force' headquarters='Sister Margaret's Bar' id=1
|
||||
Hero's team: name='Z-Force' headquarters='Sister Margaret’s Bar' id=1
|
||||
```
|
||||
|
||||
</div>
|
||||
@ -149,13 +149,10 @@ Let's say that for some reason you hate the idea of having all the database mode
|
||||
|
||||
You can also do it. 😎 There's a couple of things to keep in mind. 🤓
|
||||
|
||||
/// warning
|
||||
!!! warning
|
||||
This is a bit more advanced.
|
||||
|
||||
This is a bit more advanced.
|
||||
|
||||
If the solution above already worked for you, that might be enough for you, and you can continue in the next chapter. 🤓
|
||||
|
||||
///
|
||||
If the solution above already worked for you, that might be enough for you, and you can continue in the next chapter. 🤓
|
||||
|
||||
Let's assume that now the file structure is:
|
||||
|
||||
@ -243,7 +240,7 @@ And running that achieves the same result as before:
|
||||
$ python -m project.app
|
||||
|
||||
Created hero: id=1 age=None name='Deadpond' secret_name='Dive Wilson' team_id=1
|
||||
Hero's team: id=1 name='Z-Force' headquarters='Sister Margaret's Bar'
|
||||
Hero's team: id=1 name='Z-Force' headquarters='Sister Margaret’s Bar'
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
@ -12,7 +12,7 @@ The `team` table will look like this:
|
||||
<td>1</td><td>Preventers</td><td>Sharp Tower</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>2</td><td>Z-Force</td><td>Sister Margaret's Bar</td>
|
||||
<td>2</td><td>Z-Force</td><td>Sister Margaret’s Bar</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@ -37,33 +37,19 @@ Each row in the table `hero` will point to a row in the table `team`:
|
||||
|
||||
<img alt="table relationships" src="/img/tutorial/relationships/select/relationships2.svg">
|
||||
|
||||
/// info
|
||||
|
||||
We will later update **Spider-Boy** to add him to the **Preventers** team too, but not yet.
|
||||
|
||||
///
|
||||
!!! info
|
||||
We will later update **Spider-Boy** to add him to the **Preventers** team too, but not yet.
|
||||
|
||||
We will continue with the code in the previous example and we will add more things to it.
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/create_tables/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/create_tables/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Make sure you remove the `database.db` file before running the examples to get the same results.
|
||||
|
||||
@ -75,20 +61,6 @@ And now we will also create the teams there. 🎉
|
||||
|
||||
Let's start by creating two teams:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3-9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001_py310.py[ln:29-35]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3-9"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -97,27 +69,14 @@ Let's start by creating two teams:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This would hopefully look already familiar.
|
||||
|
||||
@ -133,20 +92,6 @@ And finally we **commit** the session to save the changes to the database.
|
||||
|
||||
Let's not forget to add this function `create_heroes()` to the `main()` function so that we run it when calling the program from the command line:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001_py310.py[ln:61-63]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -155,27 +100,14 @@ Let's not forget to add this function `create_heroes()` to the `main()` function
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Run it
|
||||
|
||||
@ -194,7 +126,7 @@ INFO Engine BEGIN (implicit)
|
||||
INFO Engine INSERT INTO team (name, headquarters) VALUES (?, ?)
|
||||
INFO Engine [generated in 0.00050s] ('Preventers', 'Sharp Tower')
|
||||
INFO Engine INSERT INTO team (name, headquarters) VALUES (?, ?)
|
||||
INFO Engine [cached since 0.002324s ago] ('Z-Force', 'Sister Margaret's Bar')
|
||||
INFO Engine [cached since 0.002324s ago] ('Z-Force', 'Sister Margaret’s Bar')
|
||||
INFO Engine COMMIT
|
||||
```
|
||||
|
||||
@ -208,20 +140,6 @@ Now let's create one hero object to start.
|
||||
|
||||
As the `Hero` class model now has a field (column, attribute) `team_id`, we can set it by using the ID field from the `Team` objects we just created before:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="12"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001_py310.py[ln:29-39]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="12"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -230,27 +148,14 @@ As the `Hero` class model now has a field (column, attribute) `team_id`, we can
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
We haven't committed this hero to the database yet, but there are already a couple of things to pay **attention** to.
|
||||
|
||||
@ -274,20 +179,6 @@ INFO Engine [generated in 0.00025s] (2,)
|
||||
|
||||
Let's now create two more heroes:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="14-20"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001_py310.py[ln:29-50]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="14-20"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -296,27 +187,14 @@ Let's now create two more heroes:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
When creating `hero_rusty_man`, we are accessing `team_preventers.id`, so that will also trigger a refresh of its data, generating an output of:
|
||||
|
||||
@ -347,21 +225,7 @@ INFO Engine COMMIT
|
||||
|
||||
Now let's refresh and print those new heroes to see their new ID pointing to their teams:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="26-28 30-32"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001_py310.py[ln:29-58]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="26-28 30-32"
|
||||
```Python hl_lines="26-28 30-32"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001.py[ln:31-60]!}
|
||||
@ -369,27 +233,15 @@ Now let's refresh and print those new heroes to see their new ID pointing to the
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
</details>
|
||||
|
||||
///
|
||||
|
||||
If we execute that in the command line, it will output:
|
||||
|
||||
|
||||
@ -16,7 +16,7 @@ The team table will look like this:
|
||||
<td>1</td><td>Preventers</td><td>Sharp Tower</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>2</td><td>Z-Force</td><td>Sister Margaret's Bar</td>
|
||||
<td>2</td><td>Z-Force</td><td>Sister Margaret’s Bar</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@ -57,45 +57,20 @@ Let's start by creating the tables in code.
|
||||
|
||||
Import the things we need from `sqlmodel` and create a new `Team` model:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="4-7"
|
||||
{!./docs_src/tutorial/connect/create_tables/tutorial001_py310.py[ln:1-7]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="6-9"
|
||||
{!./docs_src/tutorial/connect/create_tables/tutorial001.py[ln:1-9]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/create_tables/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/create_tables/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This is very similar to what we have been doing with the `Hero` model.
|
||||
|
||||
@ -114,45 +89,20 @@ Now let's create the `hero` table.
|
||||
|
||||
This is the same model we have been using up to now, we are just adding the new column `team_id`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="16"
|
||||
{!./docs_src/tutorial/connect/create_tables/tutorial001_py310.py[ln:1-16]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!./docs_src/tutorial/connect/create_tables/tutorial001.py[ln:1-18]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/create_tables/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/create_tables/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Most of that should look familiar:
|
||||
|
||||
@ -176,105 +126,49 @@ This is the name of the **table** in the database, so it is `"team"`, not the na
|
||||
|
||||
If you had a custom table name, you would use that custom table name.
|
||||
|
||||
/// info
|
||||
|
||||
You can learn about setting a custom table name for a model in the Advanced User Guide.
|
||||
|
||||
///
|
||||
!!! info
|
||||
You can learn about setting a custom table name for a model in the Advanced User Guide.
|
||||
|
||||
### Create the Tables
|
||||
|
||||
Now we can add the same code as before to create the engine and the function to create the tables:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3-4 6 9-10"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/create_tables/tutorial001_py310.py[ln:19-26]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3-4 6 9-10"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/create_tables/tutorial001.py[ln:21-28]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/create_tables/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/create_tables/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
And as before, we'll call this function from another function `main()`, and we'll add that function `main()` to the main block of the file:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3-4 7-8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/create_tables/tutorial001_py310.py[ln:29-34]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3-4 7-8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/create_tables/tutorial001.py[ln:31-36]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/create_tables/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/create_tables/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Run the Code
|
||||
|
||||
/// tip
|
||||
|
||||
Before running the code, make sure you delete the file `database.db` to make sure you start from scratch.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Before running the code, make sure you delete the file `database.db` to make sure you start from scratch.
|
||||
|
||||
If we run the code we have up to now, it will go and create the database file `database.db` and the tables in it we just defined, `team` and `hero`:
|
||||
|
||||
|
||||
@ -6,10 +6,7 @@ But the main advantage and feature of SQL databases is being able to handle rela
|
||||
|
||||
Let's see how to use **SQLModel** to manage connected data in the next chapters. 🤝
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
We will extend this further in the next group of chapters making it even more convenient to work with in Python code, using **relationship attributes**.
|
||||
|
||||
We will extend this further in the next group of chapters making it even more convenient to work with in Python code, using **relationship attributes**.
|
||||
|
||||
But you should start in this group of chapters first. 🤓
|
||||
|
||||
///
|
||||
But you should start in this group of chapters first. 🤓
|
||||
|
||||
@ -12,7 +12,7 @@ The `team` table has this data:
|
||||
<td>1</td><td>Preventers</td><td>Sharp Tower</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>2</td><td>Z-Force</td><td>Sister Margaret's Bar</td>
|
||||
<td>2</td><td>Z-Force</td><td>Sister Margaret’s Bar</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@ -35,25 +35,14 @@ And the `hero` table has this data:
|
||||
|
||||
We will continue with the code in the previous example and we will add more things to it.
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## `SELECT` Connected Data with SQL
|
||||
|
||||
@ -73,11 +62,8 @@ FROM hero, team
|
||||
WHERE hero.team_id = team.id
|
||||
```
|
||||
|
||||
/// info
|
||||
|
||||
Because we have two columns called `name`, one for `hero` and one for `team`, we can specify them with the prefix of the table name and the dot to make it explicit what we refer to.
|
||||
|
||||
///
|
||||
!!! info
|
||||
Because we have two columns called `name`, one for `hero` and one for `team`, we can specify them with the prefix of the table name and the dot to make it explicit what we refer to.
|
||||
|
||||
Notice that now in the `WHERE` part we are not comparing one column with a literal value (like `hero.name = "Deadpond"`), but we are comparing two columns.
|
||||
|
||||
@ -113,17 +99,14 @@ You can go ahead and try it in **DB Browser for SQLite**:
|
||||
|
||||
<img class="shadow" src="/img/tutorial/relationships/select/image01.png">
|
||||
|
||||
/// note
|
||||
!!! note
|
||||
Wait, what about Spider-Boy? 😱
|
||||
|
||||
Wait, what about Spider-Boy? 😱
|
||||
He doesn't have a team, so his `team_id` is `NULL` in the database. And this SQL is comparing that `NULL` from the `team_id` with all the `id` fields in the rows in the `team` table.
|
||||
|
||||
He doesn't have a team, so his `team_id` is `NULL` in the database. And this SQL is comparing that `NULL` from the `team_id` with all the `id` fields in the rows in the `team` table.
|
||||
As there's no team with an ID of `NULL`, it doesn't find a match.
|
||||
|
||||
As there's no team with an ID of `NULL`, it doesn't find a match.
|
||||
|
||||
But we'll see how to fix that later with a `LEFT JOIN`.
|
||||
|
||||
///
|
||||
But we'll see how to fix that later with a `LEFT JOIN`.
|
||||
|
||||
## Select Related Data with **SQLModel**
|
||||
|
||||
@ -135,20 +118,6 @@ Remember SQLModel's `select()` function? It can take more than one argument.
|
||||
|
||||
So, we can pass the `Hero` and `Team` model classes. And we can also use both their columns in the `.where()` part:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/select/tutorial001_py310.py[ln:61-63]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -157,27 +126,14 @@ So, we can pass the `Hero` and `Team` model classes. And we can also use both th
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/select/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/select/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Notice that in the comparison with `==` we are using the class attributes for both `Hero.team_id` and `Team.id`.
|
||||
|
||||
@ -187,20 +143,6 @@ Now we can execute it and get the `results` object.
|
||||
|
||||
And as we used `select` with two models, we will receive tuples of instances of those two models, so we can iterate over them naturally in a `for` loop:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="7"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/select/tutorial001_py310.py[ln:61-66]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="7"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -209,58 +151,28 @@ And as we used `select` with two models, we will receive tuples of instances of
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/select/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/select/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
For each iteration in the `for` loop we get a a tuple with an instance of the class `Hero` and an instance of the class `Team`.
|
||||
|
||||
And in this `for` loop we assign them to the variable `hero` and the variable `team`.
|
||||
|
||||
/// info
|
||||
!!! info
|
||||
There was a lot of research, design, and work behind **SQLModel** to make this provide the best possible developer experience.
|
||||
|
||||
There was a lot of research, design, and work behind **SQLModel** to make this provide the best possible developer experience.
|
||||
|
||||
And you should get autocompletion and inline errors in your editor for both `hero` and `team`. 🎉
|
||||
|
||||
///
|
||||
And you should get autocompletion and inline errors in your editor for both `hero` and `team`. 🎉
|
||||
|
||||
## Add It to Main
|
||||
|
||||
As always, we must remember to add this new `select_heroes()` function to the `main()` function to make sure it is executed when we call this program from the command line.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="6"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/select/tutorial001_py310.py[ln:69-72]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="6"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -269,27 +181,14 @@ As always, we must remember to add this new `select_heroes()` function to the `m
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/select/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/select/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
|
||||
## Run the Program
|
||||
@ -310,7 +209,7 @@ WHERE hero.team_id = team.id
|
||||
2021-08-09 08:55:50,682 INFO sqlalchemy.engine.Engine [no key 0.00015s] ()
|
||||
|
||||
// Print the first hero and team
|
||||
Hero: id=1 secret_name='Dive Wilson' team_id=2 name='Deadpond' age=None Team: headquarters='Sister Margaret's Bar' id=2 name='Z-Force'
|
||||
Hero: id=1 secret_name='Dive Wilson' team_id=2 name='Deadpond' age=None Team: headquarters='Sister Margaret’s Bar' id=2 name='Z-Force'
|
||||
|
||||
// Print the second hero and team
|
||||
Hero: id=2 secret_name='Tommy Sharp' team_id=1 name='Rusty-Man' age=48 Team: headquarters='Sharp Tower' id=1 name='Preventers'
|
||||
@ -382,13 +281,10 @@ Also in **DB Browser for SQLite**:
|
||||
|
||||
<img class="shadow" src="/img/tutorial/relationships/select/image02.png">
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
Why bother with all this if the result is the same?
|
||||
|
||||
Why bother with all this if the result is the same?
|
||||
|
||||
This `JOIN` will be useful in a bit to be able to also get Spider-Boy, even if he doesn't have a team.
|
||||
|
||||
///
|
||||
This `JOIN` will be useful in a bit to be able to also get Spider-Boy, even if he doesn't have a team.
|
||||
|
||||
## Join Tables in **SQLModel**
|
||||
|
||||
@ -396,20 +292,6 @@ The same way there's a `.where()` available when using `select()`, there's also
|
||||
|
||||
And in SQLModel (actually SQLAlchemy), when using the `.join()`, because we already declared what is the `foreign_key` when creating the models, we don't have to pass an `ON` part, it is inferred automatically:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/select/tutorial002_py310.py[ln:61-66]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -418,27 +300,14 @@ And in SQLModel (actually SQLAlchemy), when using the `.join()`, because we alre
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/select/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/select/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Also notice that we are still including `Team` in the `select(Hero, Team)`, because we still want to access that data.
|
||||
|
||||
@ -459,7 +328,7 @@ FROM hero JOIN team ON team.id = hero.team_id
|
||||
INFO Engine [no key 0.00032s] ()
|
||||
|
||||
// Print the first hero and team
|
||||
Hero: id=1 secret_name='Dive Wilson' team_id=2 name='Deadpond' age=None Team: headquarters='Sister Margaret's Bar' id=2 name='Z-Force'
|
||||
Hero: id=1 secret_name='Dive Wilson' team_id=2 name='Deadpond' age=None Team: headquarters='Sister Margaret’s Bar' id=2 name='Z-Force'
|
||||
|
||||
// Print the second hero and team
|
||||
Hero: id=2 secret_name='Tommy Sharp' team_id=1 name='Rusty-Man' age=48 Team: headquarters='Sharp Tower' id=1 name='Preventers'
|
||||
@ -551,11 +420,8 @@ And that would return the following result, including **Spider-Boy** 🎉:
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
/// tip
|
||||
|
||||
The only difference between this query and the previous is that extra `LEFT OUTER`.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
The only difference between this query and the previous is that extra `LEFT OUTER`.
|
||||
|
||||
And here's another of the SQL variations, you could write `LEFT OUTER JOIN` or just `LEFT JOIN`, it means the same.
|
||||
|
||||
@ -565,20 +431,6 @@ Now let's replicate the same query in **SQLModel**.
|
||||
|
||||
`.join()` has a parameter we can use `isouter=True` to make the `JOIN` be a `LEFT OUTER JOIN`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/select/tutorial003_py310.py[ln:61-66]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -587,27 +439,14 @@ Now let's replicate the same query in **SQLModel**.
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/select/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/select/tutorial003.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
And if we run it, it will output:
|
||||
|
||||
@ -625,7 +464,7 @@ FROM hero LEFT OUTER JOIN team ON team.id = hero.team_id
|
||||
INFO Engine [no key 0.00051s] ()
|
||||
|
||||
// Print the first hero and team
|
||||
Hero: id=1 secret_name='Dive Wilson' team_id=2 name='Deadpond' age=None Team: headquarters='Sister Margaret's Bar' id=2 name='Z-Force'
|
||||
Hero: id=1 secret_name='Dive Wilson' team_id=2 name='Deadpond' age=None Team: headquarters='Sister Margaret’s Bar' id=2 name='Z-Force'
|
||||
// Print the second hero and team
|
||||
Hero: id=2 secret_name='Tommy Sharp' team_id=1 name='Rusty-Man' age=48 Team: headquarters='Sharp Tower' id=1 name='Preventers'
|
||||
// Print the third hero and team, we included Spider-Boy 🎉
|
||||
@ -654,20 +493,6 @@ But we would still be able to **filter** the rows with it. 🤓
|
||||
|
||||
We could even add some additional `.where()` after `.join()` to filter the data more, for example to return only the heroes from one team:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/select/tutorial004_py310.py[ln:61-66]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -676,27 +501,14 @@ We could even add some additional `.where()` after `.join()` to filter the data
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/select/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/select/tutorial004.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Here we are **filtering** with `.where()` to get only the heroes that belong to the **Preventers** team.
|
||||
|
||||
@ -727,20 +539,6 @@ Preventer Hero: id=2 secret_name='Tommy Sharp' team_id=1 name='Rusty-Man' age=48
|
||||
|
||||
By putting the `Team` in `select()` we tell **SQLModel** and the database that we want the team data too.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/select/tutorial005_py310.py[ln:61-66]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -749,27 +547,14 @@ By putting the `Team` in `select()` we tell **SQLModel** and the database that w
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/select/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/select/tutorial005.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
And if we run that, it will output:
|
||||
|
||||
|
||||
@ -10,7 +10,7 @@ We currently have a `team` table:
|
||||
<td>1</td><td>Preventers</td><td>Sharp Tower</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>2</td><td>Z-Force</td><td>Sister Margaret's Bar</td>
|
||||
<td>2</td><td>Z-Force</td><td>Sister Margaret’s Bar</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@ -35,25 +35,14 @@ Let's see how to **remove** connections between rows in tables.
|
||||
|
||||
We will continue with the code from the previous chapter.
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/update/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/update/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Break a Connection
|
||||
|
||||
@ -63,24 +52,6 @@ Let's say **Spider-Boy** is tired of the lack of friendly neighbors and wants to
|
||||
|
||||
We can simply set the `team_id` to `None`, and now it doesn't have a connection with the team:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/delete/tutorial001_py310.py[ln:29-30]!}
|
||||
|
||||
# Previous code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/connect/delete/tutorial001_py310.py[ln:66-70]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -93,27 +64,14 @@ We can simply set the `team_id` to `None`, and now it doesn't have a connection
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/delete/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/delete/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Again, we just **assign** a value to that field attribute `team_id`, now the value is `None`, which means `NULL` in the database. Then we `add()` the hero to the session, and then `commit()`.
|
||||
|
||||
|
||||
@ -10,7 +10,7 @@ At this point we have a `team` table:
|
||||
<td>1</td><td>Preventers</td><td>Sharp Tower</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>2</td><td>Z-Force</td><td>Sister Margaret's Bar</td>
|
||||
<td>2</td><td>Z-Force</td><td>Sister Margaret’s Bar</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@ -37,25 +37,14 @@ Now we'll see how to **update** those connections between rows tables.
|
||||
|
||||
We will continue with the code we used to create some heroes, and we'll update them.
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Assign a Team to a Hero
|
||||
|
||||
@ -63,24 +52,6 @@ Let's say that **Tommy Sharp** uses his "rich uncle" charms to recruit **Spider-
|
||||
|
||||
Doing it is just like updating any other field:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/update/tutorial001_py310.py[ln:29-30]!}
|
||||
|
||||
# Previous code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/connect/update/tutorial001_py310.py[ln:60-64]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -93,27 +64,14 @@ Doing it is just like updating any other field:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/update/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/update/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
We can simply **assign** a value to that field attribute `team_id`, then `add()` the hero to the session, and then `commit()`.
|
||||
|
||||
|
||||
@ -42,11 +42,8 @@ Click the button <kbd>New Database</kbd>.
|
||||
|
||||
A dialog should show up. Go to the [project directory you created](./index.md#create-a-project){.internal-link target=_blank} and save the file with a name of `database.db`.
|
||||
|
||||
/// tip
|
||||
|
||||
It's common to save SQLite database files with an extension of `.db`. Sometimes also `.sqlite`.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
It's common to save SQLite database files with an extension of `.db`. Sometimes also `.sqlite`.
|
||||
|
||||
## Create a Table
|
||||
|
||||
@ -125,8 +122,6 @@ And delete that `./database.db` file in your project directory.
|
||||
|
||||
And click again on <kbd>New Database</kbd>.
|
||||
|
||||
Save the file with the name `database.db` again.
|
||||
|
||||
This time, if you see the dialog to create a new table, just close it by clicking the <kbd>Cancel</kbd> button.
|
||||
|
||||
And now, go to the tab <kbd>Execute SQL</kbd>.
|
||||
|
||||
@ -33,27 +33,34 @@ The first thing we need to do is create a class to represent the data in the tab
|
||||
|
||||
A class like this that represents some data is commonly called a **model**.
|
||||
|
||||
/// tip
|
||||
|
||||
That's why this package is called `SQLModel`. Because it's mainly used to create **SQL Models**.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
That's why this package is called `SQLModel`. Because it's mainly used to create **SQL Models**.
|
||||
|
||||
For that, we will import `SQLModel` (plus other things we will also use) and create a class `Hero` that inherits from `SQLModel` and represents the **table model** for our heroes:
|
||||
|
||||
{* ./docs_src/tutorial/create_db_and_table/tutorial001_py310.py ln[1:8] hl[1,4] *}
|
||||
```Python hl_lines="3 6"
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial001.py[ln:1-10]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial001.py!}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
This class `Hero` **represents the table** for our heroes. And each instance we create later will **represent a row** in the table.
|
||||
|
||||
We use the config `table=True` to tell **SQLModel** that this is a **table model**, it represents a table.
|
||||
|
||||
/// info
|
||||
!!! info
|
||||
It's also possible to have models without `table=True`, those would be only **data models**, without a table in the database, they would not be **table models**.
|
||||
|
||||
It's also possible to have models without `table=True`, those would be only **data models**, without a table in the database, they would not be **table models**.
|
||||
|
||||
Those **data models** will be **very useful later**, but for now, we'll just keep adding the `table=True` configuration.
|
||||
|
||||
///
|
||||
Those **data models** will be **very useful later**, but for now, we'll just keep adding the `table=True` configuration.
|
||||
|
||||
## Define the Fields, Columns
|
||||
|
||||
@ -63,13 +70,26 @@ The name of each of these variables will be the name of the column in the table.
|
||||
|
||||
And the type of each of them will also be the type of table column:
|
||||
|
||||
{* ./docs_src/tutorial/create_db_and_table/tutorial001_py310.py ln[1:8] hl[1,5:8] *}
|
||||
```Python hl_lines="1 3 7-10"
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial001.py[ln:1-10]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial001.py!}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
Let's now see with more detail these field/column declarations.
|
||||
|
||||
### Optional Fields, Nullable Columns
|
||||
|
||||
Let's start with `age`, notice that it has a type of `int | None (or Optional[int])`.
|
||||
Let's start with `age`, notice that it has a type of `Optional[int]`.
|
||||
|
||||
And we import that `Optional` from the `typing` standard module.
|
||||
|
||||
@ -77,13 +97,23 @@ That is the standard way to declare that something "could be an `int` or `None`"
|
||||
|
||||
And we also set the default value of `age` to `None`.
|
||||
|
||||
{* ./docs_src/tutorial/create_db_and_table/tutorial001_py310.py ln[1:8] hl[8] *}
|
||||
```Python hl_lines="1 10"
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial001.py[ln:1-10]!}
|
||||
|
||||
/// tip
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
We also define `id` with `Optional`. But we will talk about `id` below.
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
///
|
||||
```Python
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial001.py!}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
!!! tip
|
||||
We also define `id` with `Optional`. But we will talk about `id` below.
|
||||
|
||||
This way, we tell **SQLModel** that `age` is not required when validating data and that it has a default value of `None`.
|
||||
|
||||
@ -91,13 +121,10 @@ And we also tell it that, in the SQL database, the default value of `age` is `NU
|
||||
|
||||
So, this column is "nullable" (can be set to `NULL`).
|
||||
|
||||
/// info
|
||||
!!! info
|
||||
In terms of **Pydantic**, `age` is an **optional field**.
|
||||
|
||||
In terms of **Pydantic**, `age` is an **optional field**.
|
||||
|
||||
In terms of **SQLAlchemy**, `age` is a **nullable column**.
|
||||
|
||||
///
|
||||
In terms of **SQLAlchemy**, `age` is a **nullable column**.
|
||||
|
||||
### Primary Key `id`
|
||||
|
||||
@ -107,7 +134,20 @@ So, we need to mark `id` as the **primary key**.
|
||||
|
||||
To do that, we use the special `Field` function from `sqlmodel` and set the argument `primary_key=True`:
|
||||
|
||||
{* ./docs_src/tutorial/create_db_and_table/tutorial001_py310.py ln[1:8] hl[1,5] *}
|
||||
```Python hl_lines="3 7"
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial001.py[ln:1-10]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial001.py!}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
That way, we tell **SQLModel** that this `id` field/column is the primary key of the table.
|
||||
|
||||
@ -150,21 +190,31 @@ If you have a server database (for example PostgreSQL or MySQL), the **engine**
|
||||
|
||||
Creating the **engine** is very simple, just call `create_engine()` with a URL for the database to use:
|
||||
|
||||
{* ./docs_src/tutorial/create_db_and_table/tutorial001_py310.py ln[1:16] hl[1,14] *}
|
||||
```Python hl_lines="3 16"
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial001.py[ln:1-16]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial001.py!}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
You should normally have a single **engine** object for your whole application and re-use it everywhere.
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
There's another related thing called a **Session** that normally should *not* be a single object per application.
|
||||
|
||||
There's another related thing called a **Session** that normally should *not* be a single object per application.
|
||||
|
||||
But we will talk about it later.
|
||||
|
||||
///
|
||||
But we will talk about it later.
|
||||
|
||||
### Engine Database URL
|
||||
|
||||
Each supported database has its own URL type. For example, for **SQLite** it is `sqlite:///` followed by the file path. For example:
|
||||
Each supported database has it's own URL type. For example, for **SQLite** it is `sqlite:///` followed by the file path. For example:
|
||||
|
||||
* `sqlite:///database.db`
|
||||
* `sqlite:///databases/local/application.db`
|
||||
@ -174,7 +224,20 @@ SQLite supports a special database that lives all *in memory*. Hence, it's very
|
||||
|
||||
* `sqlite://`
|
||||
|
||||
{* ./docs_src/tutorial/create_db_and_table/tutorial001_py310.py ln[1:16] hl[11:12,14] *}
|
||||
```Python hl_lines="13-14 16"
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial001.py[ln:1-19]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial001.py!}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
You can read a lot more about all the databases supported by **SQLAlchemy** (and that way supported by **SQLModel**) in the <a href="https://docs.sqlalchemy.org/en/14/core/engines.html" class="external-link" target="_blank">SQLAlchemy documentation</a>.
|
||||
|
||||
@ -186,7 +249,20 @@ It will make the engine print all the SQL statements it executes, which can help
|
||||
|
||||
It is particularly useful for **learning** and **debugging**:
|
||||
|
||||
{* ./docs_src/tutorial/create_db_and_table/tutorial001_py310.py ln[1:16] hl[14] *}
|
||||
```Python hl_lines="16"
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial001.py[ln:1-16]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial001.py!}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
But in production, you would probably want to remove `echo=True`:
|
||||
|
||||
@ -196,15 +272,12 @@ engine = create_engine(sqlite_url)
|
||||
|
||||
### Engine Technical Details
|
||||
|
||||
/// tip
|
||||
|
||||
If you didn't know about SQLAlchemy before and are just learning **SQLModel**, you can probably skip this section, scroll below.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
If you didn't know about SQLAlchemy before and are just learning **SQLModel**, you can probably skip this section, scroll below.
|
||||
|
||||
You can read a lot more about the engine in the <a href="https://docs.sqlalchemy.org/en/14/tutorial/engine.html" class="external-link" target="_blank">SQLAlchemy documentation</a>.
|
||||
|
||||
**SQLModel** defines its own `create_engine()` function. It is the same as SQLAlchemy's `create_engine()`, but with the difference that it defaults to use `future=True` (which means that it uses the style of the latest SQLAlchemy, 1.4, and the future 2.0).
|
||||
**SQLModel** defines it's own `create_engine()` function. It is the same as SQLAlchemy's `create_engine()`, but with the difference that it defaults to use `future=True` (which means that it uses the style of the latest SQLAlchemy, 1.4, and the future 2.0).
|
||||
|
||||
And SQLModel's version of `create_engine()` is type annotated internally, so your editor will be able to help you with autocompletion and inline errors.
|
||||
|
||||
@ -212,17 +285,16 @@ And SQLModel's version of `create_engine()` is type annotated internally, so you
|
||||
|
||||
Now everything is in place to finally create the database and table:
|
||||
|
||||
{* ./docs_src/tutorial/create_db_and_table/tutorial001_py310.py hl[16] *}
|
||||
```Python hl_lines="18"
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial001.py!}
|
||||
```
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
Creating the engine doesn't create the `database.db` file.
|
||||
|
||||
Creating the engine doesn't create the `database.db` file.
|
||||
But once we run `SQLModel.metadata.create_all(engine)`, it creates the `database.db` file **and** creates the `hero` table in that database.
|
||||
|
||||
But once we run `SQLModel.metadata.create_all(engine)`, it creates the `database.db` file **and** creates the `hero` table in that database.
|
||||
|
||||
Both things are done in this single step.
|
||||
|
||||
///
|
||||
Both things are done in this single step.
|
||||
|
||||
Let's unwrap that:
|
||||
|
||||
@ -323,13 +395,17 @@ Let's run the program to see it all working.
|
||||
|
||||
Put the code it in a file `app.py` if you haven't already.
|
||||
|
||||
{* ./docs_src/tutorial/create_db_and_table/tutorial001_py310.py *}
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
/// tip
|
||||
```Python
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial001.py!}
|
||||
```
|
||||
|
||||
Remember to [activate the virtual environment](./index.md#create-a-python-virtual-environment){.internal-link target=_blank} before running it.
|
||||
</details>
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Remember to [activate the virtual environment](./index.md#create-a-python-virtual-environment){.internal-link target=_blank} before running it.
|
||||
|
||||
Now run the program with Python:
|
||||
|
||||
@ -366,23 +442,20 @@ INFO Engine COMMIT
|
||||
|
||||
</div>
|
||||
|
||||
/// info
|
||||
!!! info
|
||||
I simplified the output above a bit to make it easier to read.
|
||||
|
||||
I simplified the output above a bit to make it easier to read.
|
||||
But in reality, instead of showing:
|
||||
|
||||
But in reality, instead of showing:
|
||||
```
|
||||
INFO Engine BEGIN (implicit)
|
||||
```
|
||||
|
||||
```
|
||||
INFO Engine BEGIN (implicit)
|
||||
```
|
||||
it would show something like:
|
||||
|
||||
it would show something like:
|
||||
|
||||
```
|
||||
2021-07-25 21:37:39,175 INFO sqlalchemy.engine.Engine BEGIN (implicit)
|
||||
```
|
||||
|
||||
///
|
||||
```
|
||||
2021-07-25 21:37:39,175 INFO sqlalchemy.engine.Engine BEGIN (implicit)
|
||||
```
|
||||
|
||||
### `TEXT` or `VARCHAR`
|
||||
|
||||
@ -390,7 +463,7 @@ In the example in the previous chapter we created the table using `TEXT` for som
|
||||
|
||||
But in this output SQLAlchemy is using `VARCHAR` instead. Let's see what's going on.
|
||||
|
||||
Remember that [each SQL Database has some different variations in what they support?](../databases.md#sql-the-language){.internal-link target=_blank}
|
||||
Remember that [each SQL Database has some different variations in what they support?](../databases/#sql-the-language){.internal-link target=_blank}
|
||||
|
||||
This is one of the differences. Each database supports some particular **data types**, like `INTEGER` and `TEXT`.
|
||||
|
||||
@ -406,11 +479,8 @@ Additional to the difference between those two data types, some databases like M
|
||||
|
||||
To make it easier to start using **SQLModel** right away independent of the database you use (even with MySQL), and without any extra configurations, by default, `str` fields are interpreted as `VARCHAR` in most databases and `VARCHAR(255)` in MySQL, this way you know the same class will be compatible with the most popular databases without extra effort.
|
||||
|
||||
/// tip
|
||||
|
||||
You will learn how to change the maximum length of string columns later in the Advanced Tutorial - User Guide.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
You will learn how to change the maximum length of string columns later in the Advanced Tutorial - User Guide.
|
||||
|
||||
### Verify the Database
|
||||
|
||||
@ -428,7 +498,20 @@ In this example it's just the `SQLModel.metadata.create_all(engine)`.
|
||||
|
||||
Let's put it in a function `create_db_and_tables()`:
|
||||
|
||||
{* ./docs_src/tutorial/create_db_and_table/tutorial002_py310.py ln[1:18] hl[17:18] *}
|
||||
```Python hl_lines="19-20"
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial002.py[ln:1-20]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial002.py!}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
If `SQLModel.metadata.create_all(engine)` was not in a function and we tried to import something from this module (from this file) in another, it would try to create the database and table **every time** we executed that other file that imported this module.
|
||||
|
||||
@ -436,11 +519,8 @@ We don't want that to happen like that, only when we **intend** it to happen, th
|
||||
|
||||
Now we would be able to, for example, import the `Hero` class in some other file without having those **side effects**.
|
||||
|
||||
/// tip
|
||||
|
||||
😅 **Spoiler alert**: The function is called `create_db_and_tables()` because we will have more **tables** in the future with other classes apart from `Hero`. 🚀
|
||||
|
||||
///
|
||||
!!! tip
|
||||
😅 **Spoiler alert**: The function is called `create_db_and_tables()` because we will have more **tables** in the future with other classes apart from `Hero`. 🚀
|
||||
|
||||
### Create Data as a Script
|
||||
|
||||
@ -448,17 +528,16 @@ We prevented the side effects when importing something from your `app.py` file.
|
||||
|
||||
But we still want it to **create the database and table** when we call it with Python directly as an independent script from the terminal, just as as above.
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
Think of the word **script** and **program** as interchangeable.
|
||||
|
||||
Think of the word **script** and **program** as interchangeable.
|
||||
|
||||
The word **script** often implies that the code could be run independently and easily. Or in some cases it refers to a relatively simple program.
|
||||
|
||||
///
|
||||
The word **script** often implies that the code could be run independently and easily. Or in some cases it refers to a relatively simple program.
|
||||
|
||||
For that we can use the special variable `__name__` in an `if` block:
|
||||
|
||||
{* ./docs_src/tutorial/create_db_and_table/tutorial002_py310.py hl[21:22] *}
|
||||
```Python hl_lines="23-24"
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial002.py!}
|
||||
```
|
||||
|
||||
### About `__name__ == "__main__"`
|
||||
|
||||
@ -480,13 +559,10 @@ $ python app.py
|
||||
from app import Hero
|
||||
```
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
That `if` block using `if __name__ == "__main__":` is sometimes called the "**main block**".
|
||||
|
||||
That `if` block using `if __name__ == "__main__":` is sometimes called the "**main block**".
|
||||
|
||||
The official name (in the <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">Python docs</a>) is "**Top-level script environment**".
|
||||
|
||||
///
|
||||
The official name (in the <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">Python docs</a>) is "**Top-level script environment**".
|
||||
|
||||
#### More details
|
||||
|
||||
@ -538,11 +614,8 @@ if __name__ == "__main__":
|
||||
|
||||
...will **not** be executed.
|
||||
|
||||
/// info
|
||||
|
||||
For more information, check <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">the official Python docs</a>.
|
||||
|
||||
///
|
||||
!!! info
|
||||
For more information, check <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">the official Python docs</a>.
|
||||
|
||||
## Last Review
|
||||
|
||||
@ -552,31 +625,14 @@ But now we can import things from this module in other files.
|
||||
|
||||
Now, let's give the code a final look:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```{.python .annotate}
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
{!./docs_src/tutorial/create_db_and_table/annotations/en/tutorial003.md!}
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```{.python .annotate}
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial003.py!}
|
||||
```
|
||||
|
||||
{!./docs_src/tutorial/create_db_and_table/annotations/en/tutorial003.md!}
|
||||
|
||||
////
|
||||
|
||||
/// tip
|
||||
|
||||
Review what each line does by clicking each number bubble in the code. 👆
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Review what each line does by clicking each number bubble in the code. 👆
|
||||
|
||||
## Recap
|
||||
|
||||
|
||||
@ -6,25 +6,14 @@ Now let's delete some data using **SQLModel**.
|
||||
|
||||
As before, we'll continue from where we left off with the previous code.
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/update/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/update/tutorial003.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Remember to remove the `database.db` file before running the examples to get the same results.
|
||||
|
||||
@ -74,20 +63,6 @@ To get the same results, delete the `database.db` file before running the exampl
|
||||
|
||||
We'll start by selecting the hero `"Spider-Youngster"` that we updated in the previous chapter, this is the one we will delete:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/delete/tutorial001_py310.py[ln:70-75]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -96,69 +71,31 @@ We'll start by selecting the hero `"Spider-Youngster"` that we updated in the pr
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/delete/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/delete/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
As this is a new function `delete_heroes()`, we'll also add it to the `main()` function so that we call it when executing the program from the command line:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="7"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/delete/tutorial001_py310.py[ln:90-98]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="7"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/delete/tutorial001.py[ln:92-100]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/delete/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/delete/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
That will print the same existing hero **Spider-Youngster**:
|
||||
|
||||
@ -186,20 +123,6 @@ Hero: name='Spider-Youngster' secret_name='Pedro Parqueador' age=16 id=2
|
||||
|
||||
Now, very similar to how we used `session.add()` to add or update new heroes, we can use `session.delete()` to delete the hero from the session:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="10"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/delete/tutorial001_py310.py[ln:70-77]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="10"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -208,27 +131,14 @@ Now, very similar to how we used `session.add()` to add or update new heroes, we
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/delete/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/delete/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Commit the Session
|
||||
|
||||
@ -236,20 +146,6 @@ To save the current changes in the session, **commit** it.
|
||||
|
||||
This will save all the changes stored in the **session**, like the deleted hero:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="11"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/delete/tutorial001_py310.py[ln:70-78]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="11"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -258,27 +154,14 @@ This will save all the changes stored in the **session**, like the deleted hero:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/delete/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/delete/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
The same as we have seen before, `.commit()` will also save anything else that was added to the session. Including updates, or created heroes.
|
||||
|
||||
@ -313,20 +196,6 @@ As the object is not connected to the session, it is not marked as "expired", th
|
||||
|
||||
Because of that, the object still contains its attributes with the data in it, so we can print it:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="13"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/delete/tutorial001_py310.py[ln:70-80]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="13"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -335,27 +204,14 @@ Because of that, the object still contains its attributes with the data in it, s
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/delete/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/delete/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This will output:
|
||||
|
||||
@ -378,20 +234,6 @@ Deleted hero: name='Spider-Youngster' secret_name='Pedro Parqueador' age=16 id=2
|
||||
|
||||
To confirm if it was deleted, now let's query the database again, with the same `"Spider-Youngster"` name:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="15-17"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/delete/tutorial001_py310.py[ln:70-84]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="15-17"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -400,27 +242,14 @@ To confirm if it was deleted, now let's query the database again, with the same
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/delete/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/delete/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Here we are using `results.first()` to get the first object found (in case it found multiple) or `None`, if it didn't find anything.
|
||||
|
||||
@ -457,20 +286,6 @@ Now let's just confirm that, indeed, no hero was found in the database with that
|
||||
|
||||
We'll do it by checking that the "first" item in the `results` is `None`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="19-20"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/delete/tutorial001_py310.py[ln:70-87]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="19-20"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -479,27 +294,14 @@ We'll do it by checking that the "first" item in the `results` is `None`:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/delete/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/delete/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This will output:
|
||||
|
||||
@ -525,31 +327,14 @@ INFO Engine ROLLBACK
|
||||
|
||||
Now let's review all that code:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```{ .python .annotate hl_lines="70-88" }
|
||||
{!./docs_src/tutorial/delete/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
{!./docs_src/tutorial/delete/annotations/en/tutorial002.md!}
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```{ .python .annotate hl_lines="72-90" }
|
||||
{!./docs_src/tutorial/delete/tutorial002.py!}
|
||||
```
|
||||
|
||||
{!./docs_src/tutorial/delete/annotations/en/tutorial002.md!}
|
||||
|
||||
////
|
||||
|
||||
/// tip
|
||||
|
||||
Check out the number bubbles to see what is done by each line of code.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Check out the number bubbles to see what is done by each line of code.
|
||||
|
||||
## Recap
|
||||
|
||||
|
||||
@ -12,32 +12,6 @@ We get a `hero_id` from the path parameter and verify if it exists, just as we d
|
||||
|
||||
And if we actually find a hero, we just delete it with the **session**.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3-11"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/delete/tutorial001_py310.py[ln:89-97]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3-11"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/delete/tutorial001_py39.py[ln:91-99]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3-11"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -46,35 +20,14 @@ And if we actually find a hero, we just delete it with the **session**.
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/delete/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/delete/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/delete/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
After deleting it successfully, we just return a response of:
|
||||
|
||||
|
||||
@ -8,11 +8,8 @@ So, we probably want to limit it.
|
||||
|
||||
Let's use the same **offset** and **limit** we learned about in the previous tutorial chapters for the API.
|
||||
|
||||
/// info
|
||||
|
||||
In many cases, this is also called **pagination**.
|
||||
|
||||
///
|
||||
!!! info
|
||||
In many cases, this is also called **pagination**.
|
||||
|
||||
## Add a Limit and Offset to the Query Parameters
|
||||
|
||||
@ -22,36 +19,6 @@ By default, we will return the first results from the database, so `offset` will
|
||||
|
||||
And by default, we will return a maximum of `100` heroes, so `limit` will have a default value of `100`.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="1 7 9"
|
||||
{!./docs_src/tutorial/fastapi/limit_and_offset/tutorial001_py310.py[ln:1-2]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/limit_and_offset/tutorial001_py310.py[ln:52-56]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3 9 11"
|
||||
{!./docs_src/tutorial/fastapi/limit_and_offset/tutorial001_py39.py[ln:1-4]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/limit_and_offset/tutorial001_py39.py[ln:54-58]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3 9 11"
|
||||
{!./docs_src/tutorial/fastapi/limit_and_offset/tutorial001.py[ln:1-4]!}
|
||||
|
||||
@ -62,35 +29,14 @@ And by default, we will return a maximum of `100` heroes, so `limit` will have a
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/limit_and_offset/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/limit_and_offset/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/limit_and_offset/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
We want to allow clients to set different `offset` and `limit` values.
|
||||
|
||||
@ -100,15 +46,12 @@ So, to prevent it, we add additional validation to the `limit` query parameter,
|
||||
|
||||
This way, a client can decide to take fewer heroes if they want, but not more.
|
||||
|
||||
/// info
|
||||
!!! info
|
||||
If you need to refresh how query parameters and their validation work, check out the docs in FastAPI:
|
||||
|
||||
If you need to refresh how query parameters and their validation work, check out the docs in FastAPI:
|
||||
|
||||
* <a href="https://fastapi.tiangolo.com/tutorial/query-params/" class="external-link" target="_blank">Query Parameters</a>
|
||||
* <a href="https://fastapi.tiangolo.com/tutorial/query-params-str-validations/" class="external-link" target="_blank">Query Parameters and String Validations</a>
|
||||
* <a href="https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/" class="external-link" target="_blank">Path Parameters and Numeric Validations</a>
|
||||
|
||||
///
|
||||
* <a href="https://fastapi.tiangolo.com/tutorial/query-params/" class="external-link" target="_blank">Query Parameters</a>
|
||||
* <a href="https://fastapi.tiangolo.com/tutorial/query-params-str-validations/" class="external-link" target="_blank">Query Parameters and String Validations</a>
|
||||
* <a href="https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/" class="external-link" target="_blank">Path Parameters and Numeric Validations</a>
|
||||
|
||||
## Check the Docs UI
|
||||
|
||||
|
||||
@ -98,7 +98,7 @@ But we also want to have a `HeroCreate` for the data we want to receive when **c
|
||||
* `secret_name`, required
|
||||
* `age`, optional
|
||||
|
||||
And we want to have a `HeroPublic` with the `id` field, but this time annotated with `id: int`, instead of `id: Optional[int]`, to make it clear that it is required in responses **read** from the clients:
|
||||
And we want to have a `HeroRead` with the `id` field, but this time annotated with `id: int`, instead of `id: Optional[int]`, to make it clear that it is required in responses **read** from the clients:
|
||||
|
||||
* `id`, required
|
||||
* `name`, required
|
||||
@ -109,36 +109,6 @@ And we want to have a `HeroPublic` with the `id` field, but this time annotated
|
||||
|
||||
The simplest way to solve it could be to create **multiple models**, each one with all the corresponding fields:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5-9 12-15 18-22"
|
||||
# This would work, but there's a better option below 🚨
|
||||
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial001_py310.py[ln:5-22]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="5-9 12-15 18-22"
|
||||
# This would work, but there's a better option below 🚨
|
||||
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial001_py39.py[ln:7-24]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5-9 12-15 18-22"
|
||||
# This would work, but there's a better option below 🚨
|
||||
|
||||
@ -149,49 +119,25 @@ The simplest way to solve it could be to create **multiple models**, each one wi
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Here's the important detail, and probably the most important feature of **SQLModel**: only `Hero` is declared with `table = True`.
|
||||
|
||||
This means that the class `Hero` represents a **table** in the database. It is both a **Pydantic** model and a **SQLAlchemy** model.
|
||||
|
||||
But `HeroCreate` and `HeroPublic` don't have `table = True`. They are only **data models**, they are only **Pydantic** models. They won't be used with the database, but only to declare data schemas for the API (or for other uses).
|
||||
But `HeroCreate` and `HeroRead` don't have `table = True`. They are only **data models**, they are only **Pydantic** models. They won't be used with the database, but only to declare data schemas for the API (or for other uses).
|
||||
|
||||
This also means that `SQLModel.metadata.create_all()` won't create tables in the database for `HeroCreate` and `HeroPublic`, because they don't have `table = True`, which is exactly what we want. 🚀
|
||||
This also means that `SQLModel.metadata.create_all()` won't create tables in the database for `HeroCreate` and `HeroRead`, because they don't have `table = True`, which is exactly what we want. 🚀
|
||||
|
||||
/// tip
|
||||
|
||||
We will improve this code to avoid duplicating the fields, but for now we can continue learning with these models.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
We will improve this code to avoid duplicating the fields, but for now we can continue learning with these models.
|
||||
|
||||
## Use Multiple Models to Create a Hero
|
||||
|
||||
@ -199,32 +145,6 @@ Let's now see how to use these new models in the FastAPI application.
|
||||
|
||||
Let's first check how is the process to create a hero now:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3-4 6"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial001_py310.py[ln:44-51]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3-4 6"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial001_py39.py[ln:46-53]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3-4 6"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -233,66 +153,19 @@ Let's first check how is the process to create a hero now:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Let's check that in detail.
|
||||
|
||||
Now we use the type annotation `HeroCreate` for the request JSON data in the `hero` parameter of the **path operation function**.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial001_py310.py[ln:45]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial001_py39.py[ln:47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -301,45 +174,15 @@ Now we use the type annotation `HeroCreate` for the request JSON data in the `he
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
Then we create a new `Hero` (this is the actual **table** model that saves things to the database) using `Hero.from_orm()`.
|
||||
|
||||
Then we create a new `Hero` (this is the actual **table** model that saves things to the database) using `Hero.model_validate()`.
|
||||
The method `.from_orm()` reads data from another object with attributes and creates a new instance of this class, in this case `Hero`.
|
||||
|
||||
The method `.model_validate()` reads data from another object with attributes (or a dict) and creates a new instance of this class, in this case `Hero`.
|
||||
The alternative is `Hero.parse_obj()` that reads data from a dictionary.
|
||||
|
||||
In this case, we have a `HeroCreate` instance in the `hero` variable. This is an object with attributes, so we use `.model_validate()` to read those attributes.
|
||||
But as in this case, we have a `HeroCreate` instance in the `hero` variable. This is an object with attributes, so we use `.from_orm()` to read those attributes.
|
||||
|
||||
/// tip
|
||||
In versions of **SQLModel** before `0.0.14` you would use the method `.from_orm()`, but it is now deprecated and you should use `.model_validate()` instead.
|
||||
///
|
||||
|
||||
We can now create a new `Hero` instance (the one for the database) and put it in the variable `db_hero` from the data in the `hero` variable that is the `HeroCreate` instance we received from the request.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial001_py310.py[ln:47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial001_py39.py[ln:49]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
With this, we create a new `Hero` instance (the one for the database) and put it in the variable `db_hero` from the data in the `hero` variable that is the `HeroCreate` instance we received from the request.
|
||||
|
||||
```Python hl_lines="3"
|
||||
# Code above omitted 👆
|
||||
@ -349,39 +192,11 @@ We can now create a new `Hero` instance (the one for the database) and put it in
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
Then we just `add` it to the **session**, `commit`, and `refresh` it, and finally, we return the same `db_hero` variable that has the just refreshed `Hero` instance.
|
||||
|
||||
Because it is just refreshed, it has the `id` field set with a new ID taken from the database.
|
||||
|
||||
And now that we return it, FastAPI will validate the data with the `response_model`, which is a `HeroPublic`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial001_py310.py[ln:44]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial001_py39.py[ln:46]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
And now that we return it, FastAPI will validate the data with the `response_model`, which is a `HeroRead`:
|
||||
|
||||
```Python hl_lines="3"
|
||||
# Code above omitted 👆
|
||||
@ -391,17 +206,12 @@ And now that we return it, FastAPI will validate the data with the `response_mod
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
This will validate that all the data that we promised is there and will remove any data we didn't declare.
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
This filtering could be very important and could be a very good security feature, for example, to make sure you filter private data, hashed passwords, etc.
|
||||
|
||||
This filtering could be very important and could be a very good security feature, for example, to make sure you filter private data, hashed passwords, etc.
|
||||
|
||||
You can read more about it in the <a href="https://fastapi.tiangolo.com/tutorial/response-model/" class="external-link" target="_blank">FastAPI docs about Response Model</a>.
|
||||
|
||||
///
|
||||
You can read more about it in the <a href="https://fastapi.tiangolo.com/tutorial/response-model/" class="external-link" target="_blank">FastAPI docs about Response Model</a>.
|
||||
|
||||
In particular, it will make sure that the `id` is there and that it is indeed an integer (and not `None`).
|
||||
|
||||
@ -443,32 +253,6 @@ We can see from above that they all share some **base** fields:
|
||||
|
||||
So let's create a **base** model `HeroBase` that the others can inherit from:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3-6"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py310.py[ln:5-8]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3-6"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py39.py[ln:7-10]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3-6"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -477,35 +261,14 @@ So let's create a **base** model `HeroBase` that the others can inherit from:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
As you can see, this is *not* a **table model**, it doesn't have the `table = True` config.
|
||||
|
||||
@ -515,32 +278,6 @@ But now we can create the **other models inheriting from it**, they will all sha
|
||||
|
||||
Let's start with the only **table model**, the `Hero`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="9-10"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py310.py[ln:5-12]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="9-10"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py39.py[ln:7-14]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="9-10"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -549,35 +286,14 @@ Let's start with the only **table model**, the `Hero`:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Notice that `Hero` now doesn't inherit from `SQLModel`, but from `HeroBase`.
|
||||
|
||||
@ -593,32 +309,6 @@ And those inherited fields will also be in the **autocompletion** and **inline e
|
||||
|
||||
Notice that the parent model `HeroBase` is not a **table model**, but still, we can declare `name` and `age` using `Field(index=True)`.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="4 6 9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py310.py[ln:5-12]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="4 6 9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py39.py[ln:7-14]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="4 6 9"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -627,35 +317,14 @@ Notice that the parent model `HeroBase` is not a **table model**, but still, we
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This won't affect this parent **data model** `HeroBase`.
|
||||
|
||||
@ -667,32 +336,6 @@ Now let's see the `HeroCreate` model that will be used to define the data that w
|
||||
|
||||
This is a fun one:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="13-14"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py310.py[ln:5-16]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="13-14"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py39.py[ln:7-18]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="13-14"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -701,35 +344,14 @@ This is a fun one:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
What's happening here?
|
||||
|
||||
@ -743,38 +365,12 @@ As an alternative, we could use `HeroBase` directly in the API code instead of `
|
||||
|
||||
On top of that, we could easily decide in the future that we want to receive **more data** when creating a new hero apart from the data in `HeroBase` (for example, a password), and now we already have the class to put those extra fields.
|
||||
|
||||
### The `HeroPublic` **Data Model**
|
||||
### The `HeroRead` **Data Model**
|
||||
|
||||
Now let's check the `HeroPublic` model.
|
||||
Now let's check the `HeroRead` model.
|
||||
|
||||
This one just declares that the `id` field is required when reading a hero from the API, because a hero read from the API will come from the database, and in the database it will always have an ID.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="17-18"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py310.py[ln:5-20]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="17-18"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py39.py[ln:7-22]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="17-18"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -783,39 +379,18 @@ This one just declares that the `id` field is required when reading a hero from
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Review the Updated Docs UI
|
||||
|
||||
The FastAPI code is still the same as above, we still use `Hero`, `HeroCreate`, and `HeroPublic`. But now, we define them in a smarter way with inheritance.
|
||||
The FastAPI code is still the same as above, we still use `Hero`, `HeroCreate`, and `HeroRead`. But now, we define them in a smarter way with inheritance.
|
||||
|
||||
So, we can jump to the docs UI right away and see how they look with the updated data.
|
||||
|
||||
|
||||
@ -8,37 +8,8 @@ Let's add a new *path operation* to read one single hero.
|
||||
|
||||
We want to get the hero based on the `id`, so we will use a **path parameter** `hero_id`.
|
||||
|
||||
/// info
|
||||
|
||||
If you need to refresh how *path parameters* work, including their data validation, check the <a href="https://fastapi.tiangolo.com/tutorial/path-params/" class="external-link" target="_blank">FastAPI docs about Path Parameters</a>.
|
||||
|
||||
///
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="6"
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001_py310.py[ln:1-2]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001_py310.py[ln:59-65]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001_py39.py[ln:1-4]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001_py39.py[ln:61-67]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
!!! info
|
||||
If you need to refresh how *path parameters* work, including their data validation, check the <a href="https://fastapi.tiangolo.com/tutorial/path-params/" class="external-link" target="_blank">FastAPI docs about Path Parameters</a>.
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001.py[ln:1-4]!}
|
||||
@ -48,35 +19,14 @@ If you need to refresh how *path parameters* work, including their data validati
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001.py[ln:61-67]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
For example, to get the hero with ID `2` we would send a `GET` request to:
|
||||
|
||||
@ -96,32 +46,6 @@ And to use it, we first import `HTTPException` from `fastapi`.
|
||||
|
||||
This will let the client know that they probably made a mistake on their side and requested a hero that doesn't exist in the database.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="1 9-11"
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001_py310.py[ln:1-2]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001_py310.py[ln:59-65]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3 11-13"
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001_py39.py[ln:1-4]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001_py39.py[ln:61-67]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3 11-13"
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001.py[ln:1-4]!}
|
||||
|
||||
@ -130,67 +54,20 @@ This will let the client know that they probably made a mistake on their side an
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001.py[ln:61-67]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Return the Hero
|
||||
|
||||
Then, if the hero exists, we return it.
|
||||
|
||||
And because we are using the `response_model` with `HeroPublic`, it will be validated, documented, etc.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="6 12"
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001_py310.py[ln:1-2]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001_py310.py[ln:59-65]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="8 14"
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001_py39.py[ln:1-4]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001_py39.py[ln:61-67]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
And because we are using the `response_model` with `HeroRead`, it will be validated, documented, etc.
|
||||
|
||||
```Python hl_lines="8 14"
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001.py[ln:1-4]!}
|
||||
@ -200,35 +77,14 @@ And because we are using the `response_model` with `HeroPublic`, it will be vali
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001.py[ln:61-67]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/read_one/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Check the Docs UI
|
||||
|
||||
|
||||
@ -40,59 +40,9 @@ Let's update that. 🤓
|
||||
|
||||
First, why is it that we are not getting the related data for each hero and for each team?
|
||||
|
||||
It's because we declared the `HeroPublic` with only the same base fields of the `HeroBase` plus the `id`. But it doesn't include a field `team` for the **relationship attribute**.
|
||||
It's because we declared the `HeroRead` with only the same base fields of the `HeroBase` plus the `id`. But it doesn't include a field `team` for the **relationship attribute**.
|
||||
|
||||
And the same way, we declared the `TeamPublic` with only the same base fields of the `TeamBase` plus the `id`. But it doesn't include a field `heroes` for the **relationship attribute**.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3-5 9-10 14-19 23-24"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py310.py[ln:5-7]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py310.py[ln:20-21]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py310.py[ln:29-34]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py310.py[ln:43-44]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3-5 9-10 14-19 23-24"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py39.py[ln:7-9]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py39.py[ln:22-23]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py39.py[ln:31-36]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py39.py[ln:45-46]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
And the same way, we declared the `TeamRead` with only the same base fields of the `TeamBase` plus the `id`. But it doesn't include a field `heroes` for the **relationship attribute**.
|
||||
|
||||
```Python hl_lines="3-5 9-10 14-19 23-24"
|
||||
# Code above omitted 👆
|
||||
@ -114,73 +64,18 @@ And the same way, we declared the `TeamPublic` with only the same base fields of
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Now, remember that <a href="https://fastapi.tiangolo.com/tutorial/response-model/" class="external-link" target="_blank">FastAPI uses the `response_model` to validate and **filter** the response data</a>?
|
||||
|
||||
In this case, we used `response_model=TeamPublic` and `response_model=HeroPublic`, so FastAPI will use them to filter the response data, even if we return a **table model** that includes **relationship attributes**:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3 8 12 17"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py310.py[ln:102-107]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py310.py[ln:156-161]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3 8 12 17"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py39.py[ln:104-109]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py39.py[ln:158-163]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
In this case, we used `response_model=TeamRead` and `response_model=HeroRead`, so FastAPI will use them to filter the response data, even if we return a **table model** that includes **relationship attributes**:
|
||||
|
||||
```Python hl_lines="3 8 12 17"
|
||||
# Code above omitted 👆
|
||||
@ -194,35 +89,14 @@ In this case, we used `response_model=TeamPublic` and `response_model=HeroPublic
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Don't Include All the Data
|
||||
|
||||
@ -300,36 +174,10 @@ Let's add a couple more **data models** that declare that data so we can use the
|
||||
|
||||
## Models with Relationships
|
||||
|
||||
Let's add the models `HeroPublicWithTeam` and `TeamPublicWithHeroes`.
|
||||
Let's add the models `HeroReadWithTeam` and `TeamReadWithHeroes`.
|
||||
|
||||
We'll add them **after** the other models so that we can easily reference the previous models.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3-4 7-8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/relationships/tutorial001_py310.py[ln:59-64]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3-4 7-8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/relationships/tutorial001_py39.py[ln:61-66]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3-4 7-8"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -338,45 +186,24 @@ We'll add them **after** the other models so that we can easily reference the pr
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/relationships/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/relationships/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/relationships/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
These two models are very **simple in code**, but there's a lot happening here. Let's check it out.
|
||||
|
||||
### Inheritance and Type Annotations
|
||||
|
||||
The `HeroPublicWithTeam` **inherits** from `HeroPublic`, which means that it will have the **normal fields for reading**, including the required `id` that was declared in `HeroPublic`.
|
||||
The `HeroReadWithTeam` **inherits** from `HeroRead`, which means that it will have the **normal fields for reading**, including the required `id` that was declared in `HeroRead`.
|
||||
|
||||
And then it adds the **new field** `team`, which could be `None`, and is declared with the type `TeamPublic` with the base fields for reading a team.
|
||||
And then it adds the **new field** `team`, which could be `None`, and is declared with the type `TeamRead` with the base fields for reading a team.
|
||||
|
||||
Then we do the same for the `TeamPublicWithHeroes`, it **inherits** from `TeamPublic`, and declares the **new field** `heroes`, which is a list of `HeroPublic`.
|
||||
Then we do the same for the `TeamReadWithHeroes`, it **inherits** from `TeamRead`, and declares the **new field** `heroes`, which is a list of `HeroRead`.
|
||||
|
||||
### Data Models Without Relationship Attributes
|
||||
|
||||
@ -386,11 +213,11 @@ Instead, here these are only **data models** that will tell FastAPI **which attr
|
||||
|
||||
### Reference to Other Models
|
||||
|
||||
Also, notice that the field `team` is not declared with this new `TeamPublicWithHeroes`, because that would again create that infinite recursion of data. Instead, we declare it with the normal `TeamPublic` model.
|
||||
Also, notice that the field `team` is not declared with this new `TeamReadWithHeroes`, because that would again create that infinite recursion of data. Instead, we declare it with the normal `TeamRead` model.
|
||||
|
||||
And the same for `TeamPublicWithHeroes`, the model used for the new field `heroes` uses `HeroPublic` to get only each hero's data.
|
||||
And the same for `TeamReadWithHeroes`, the model used for the new field `heroes` uses `HeroRead` to get only each hero's data.
|
||||
|
||||
This also means that, even though we have these two new models, **we still need the previous ones**, `HeroPublic` and `TeamPublic`, because we need to reference them here (and we are also using them in the rest of the *path operations*).
|
||||
This also means that, even though we have these two new models, **we still need the previous ones**, `HeroRead` and `TeamRead`, because we need to reference them here (and we are also using them in the rest of the *path operations*).
|
||||
|
||||
## Update the Path Operations
|
||||
|
||||
@ -400,40 +227,6 @@ This will tell **FastAPI** to take the object that we return from the *path oper
|
||||
|
||||
In the case of the hero, this tells FastAPI to extract the `team` too. And in the case of the team, to extract the list of `heroes` too.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3 8 12 17"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/relationships/tutorial001_py310.py[ln:111-116]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/relationships/tutorial001_py310.py[ln:165-170]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3 8 12 17"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/relationships/tutorial001_py39.py[ln:113-118]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/relationships/tutorial001_py39.py[ln:167-172]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3 8 12 17"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -446,35 +239,14 @@ In the case of the hero, this tells FastAPI to extract the `team` too. And in th
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/relationships/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/relationships/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/relationships/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Check It Out in the Docs UI
|
||||
|
||||
@ -495,7 +267,7 @@ Now we get the **team** data included:
|
||||
"id": 1,
|
||||
"team": {
|
||||
"name": "Z-Force",
|
||||
"headquarters": "Sister Margaret's Bar",
|
||||
"headquarters": "Sister Margaret’s Bar",
|
||||
"id": 1
|
||||
}
|
||||
}
|
||||
|
||||
@ -32,32 +32,6 @@ We can use `response_model` to tell FastAPI the schema of the data we want to se
|
||||
|
||||
For example, we can pass the same `Hero` **SQLModel** class (because it is also a Pydantic model):
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/response_model/tutorial001_py310.py[ln:31-37]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/response_model/tutorial001_py39.py[ln:33-39]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -66,35 +40,14 @@ For example, we can pass the same `Hero` **SQLModel** class (because it is also
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/response_model/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/response_model/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/response_model/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## List of Heroes in `response_model`
|
||||
|
||||
@ -102,34 +55,6 @@ We can also use other type annotations, the same way we can use with Pydantic fi
|
||||
|
||||
First, we import `List` from `typing` and then we declare the `response_model` with `List[Hero]`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3"
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/response_model/tutorial001_py310.py[ln:40-44]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3"
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/response_model/tutorial001_py39.py[ln:42-46]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="1 5"
|
||||
{!./docs_src/tutorial/fastapi/response_model/tutorial001.py[ln:1]!}
|
||||
|
||||
@ -140,35 +65,14 @@ First, we import `List` from `typing` and then we declare the `response_model` w
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/response_model/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/response_model/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/response_model/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## FastAPI and Response Model
|
||||
|
||||
@ -196,13 +100,10 @@ Additionally, because the schemas are defined in using a standard, there are man
|
||||
|
||||
For example, client generators, that can automatically create the code necessary to talk to your API in many languages.
|
||||
|
||||
/// info
|
||||
!!! info
|
||||
If you are curious about the standards, FastAPI generates OpenAPI, that internally uses JSON Schema.
|
||||
|
||||
If you are curious about the standards, FastAPI generates OpenAPI, that internally uses JSON Schema.
|
||||
|
||||
You can read about all that in the <a href="https://fastapi.tiangolo.com/tutorial/first-steps/#openapi" class="external-link" target="_blank">FastAPI docs - First Steps</a>.
|
||||
|
||||
///
|
||||
You can read about all that in the <a href="https://fastapi.tiangolo.com/tutorial/first-steps/#openapi" class="external-link" target="_blank">FastAPI docs - First Steps</a>.
|
||||
|
||||
## Recap
|
||||
|
||||
|
||||
@ -6,32 +6,6 @@ Before we keep adding things, let's change a bit how we get the session for each
|
||||
|
||||
Up to now, we have been creating a session in each *path operation*, in a `with` block.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/delete/tutorial001_py310.py[ln:48-55]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/delete/tutorial001_py39.py[ln:50-57]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -40,35 +14,14 @@ Up to now, we have been creating a session in each *path operation*, in a `with`
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/delete/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/delete/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/delete/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
That's perfectly fine, but in many use cases we would want to use <a href="https://fastapi.tiangolo.com/tutorial/dependencies/" class="external-link" target="_blank">FastAPI Dependencies</a>, for example to **verify** that the client is **logged in** and get the **current user** before executing any other code in the *path operation*.
|
||||
|
||||
@ -82,32 +35,6 @@ A **FastAPI** dependency is very simple, it's just a function that returns a val
|
||||
|
||||
It could use `yield` instead of `return`, and in that case **FastAPI** will make sure it executes all the code **after** the `yield`, once it is done with the request.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3-5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py310.py[ln:40-42]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3-5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py39.py[ln:42-44]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3-5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -116,35 +43,14 @@ It could use `yield` instead of `return`, and in that case **FastAPI** will make
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Use the Dependency
|
||||
|
||||
@ -152,44 +58,6 @@ Now let's make FastAPI execute a dependency and get its value in the *path opera
|
||||
|
||||
We import `Depends()` from `fastapi`. Then we use it in the *path operation function* in a **parameter**, the same way we declared parameters to get JSON bodies, path parameters, etc.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="1 13"
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py310.py[ln:1-2]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py310.py[ln:40-42]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py310.py[ln:53-59]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3 15"
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py39.py[ln:1-4]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py39.py[ln:42-44]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py39.py[ln:55-61]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3 15"
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001.py[ln:1-4]!}
|
||||
|
||||
@ -204,47 +72,23 @@ We import `Depends()` from `fastapi`. Then we use it in the *path operation func
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
</details>
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Here's a tip about that `*,` thing in the parameters.
|
||||
|
||||
/// tip
|
||||
Here we are passing the parameter `session` that has a "default value" of `Depends(get_session)` before the parameter `hero`, that doesn't have any default value.
|
||||
|
||||
Here's a tip about that `*,` thing in the parameters.
|
||||
Python would normally complain about that, but we can use the initial "parameter" `*,` to mark all the rest of the parameters as "keyword only", which solves the problem.
|
||||
|
||||
Here we are passing the parameter `session` that has a "default value" of `Depends(get_session)` before the parameter `hero`, that doesn't have any default value.
|
||||
|
||||
Python would normally complain about that, but we can use the initial "parameter" `*,` to mark all the rest of the parameters as "keyword only", which solves the problem.
|
||||
|
||||
You can read more about it in the FastAPI documentation <a href="https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#order-the-parameters-as-you-need-tricks" class="external-link" target="_blank">Path Parameters and Numeric Validations - Order the parameters as you need, tricks</a>
|
||||
|
||||
///
|
||||
You can read more about it in the FastAPI documentation <a href="https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#order-the-parameters-as-you-need-tricks" class="external-link" target="_blank">Path Parameters and Numeric Validations - Order the parameters as you need, tricks</a>
|
||||
|
||||
The value of a dependency will **only be used for one request**, FastAPI will call it right before calling your code and will give you the value from that dependency.
|
||||
|
||||
@ -260,44 +104,6 @@ And because dependencies can use `yield`, FastAPI will make sure to run the code
|
||||
|
||||
This means that in the main code of the *path operation function*, it will work equivalently to the previous version with the explicit `with` block.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="14-18"
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py310.py[ln:1-2]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py310.py[ln:40-42]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py310.py[ln:53-59]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="16-20"
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py39.py[ln:1-4]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py39.py[ln:42-44]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py39.py[ln:55-61]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="16-20"
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001.py[ln:1-4]!}
|
||||
|
||||
@ -312,78 +118,19 @@ This means that in the main code of the *path operation function*, it will work
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
In fact, you could think that all that block of code inside of the `create_hero()` function is still inside a `with` block for the **session**, because this is more or less what's happening behind the scenes.
|
||||
|
||||
But now, the `with` block is not explicitly in the function, but in the dependency above:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="7-8"
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py310.py[ln:1-2]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py310.py[ln:40-42]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py310.py[ln:53-59]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="9-10"
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py39.py[ln:1-4]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py39.py[ln:42-44]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py39.py[ln:55-61]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="9-10"
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001.py[ln:1-4]!}
|
||||
|
||||
@ -398,35 +145,14 @@ But now, the `with` block is not explicitly in the function, but in the dependen
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
We will see how this is very useful when testing the code later. ✅
|
||||
|
||||
@ -442,40 +168,6 @@ session: Session = Depends(get_session)
|
||||
|
||||
And then we remove the previous `with` block with the old **session**.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="13 24 33 42 57"
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py310.py[ln:1-2]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py310.py[ln:40-42]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py310.py[ln:53-104]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="15 26 35 44 59"
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py39.py[ln:1-4]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py39.py[ln:42-44]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py39.py[ln:55-106]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="15 26 35 44 59"
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001.py[ln:1-4]!}
|
||||
|
||||
@ -488,35 +180,14 @@ And then we remove the previous `with` block with the old **session**.
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001.py[ln:55-106]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Recap
|
||||
|
||||
|
||||
@ -10,14 +10,14 @@ FastAPI is the framework to create the **web API**.
|
||||
|
||||
But we also need another type of program to run it, it is called a "**server**". We will use **Uvicorn** for that. And we will install Uvicorn with its *standard* dependencies.
|
||||
|
||||
Then install FastAPI.
|
||||
Make sure you [have a virtual environment activated](../index.md#create-a-python-virtual-environment){.internal-link target=_blank}.
|
||||
|
||||
Make sure you create a [virtual environment](../../virtual-environments.md){.internal-link target=_blank}, activate it, and then install them, for example with:
|
||||
Then install FastAPI and Uvicorn:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install fastapi "uvicorn[standard]"
|
||||
$ python -m pip install fastapi "uvicorn[standard]"
|
||||
|
||||
---> 100%
|
||||
```
|
||||
@ -32,22 +32,6 @@ We will start with the **simplest version**, with just heroes (no teams yet).
|
||||
|
||||
This is almost the same code we have seen up to now in previous examples:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="18-19"
|
||||
|
||||
# One line of FastAPI imports here later 👈
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001_py310.py[ln:2]!}
|
||||
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001_py310.py[ln:5-20]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="20-21"
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001.py[ln:1]!}
|
||||
|
||||
@ -59,27 +43,14 @@ This is almost the same code we have seen up to now in previous examples:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
There's only one change here from the code we have used before, the `check_same_thread` in the `connect_args`.
|
||||
|
||||
@ -91,13 +62,10 @@ But here we will make sure we don't share the same **session** in more than one
|
||||
|
||||
And we also need to disable it because in **FastAPI** each request could be handled by multiple interacting threads.
|
||||
|
||||
/// info
|
||||
!!! info
|
||||
That's enough information for now, you can read more about it in the <a href="https://fastapi.tiangolo.com/async/" class="external-link" target="_blank">FastAPI docs for `async` and `await`</a>.
|
||||
|
||||
That's enough information for now, you can read more about it in the <a href="https://fastapi.tiangolo.com/async/" class="external-link" target="_blank">FastAPI docs for `async` and `await`</a>.
|
||||
|
||||
The main point is, by ensuring you **don't share** the same **session** with more than one request, the code is already safe.
|
||||
|
||||
///
|
||||
The main point is, by ensuring you **don't share** the same **session** with more than one request, the code is already safe.
|
||||
|
||||
## **FastAPI** App
|
||||
|
||||
@ -107,22 +75,6 @@ We will import the `FastAPI` class from `fastapi`.
|
||||
|
||||
And then create an `app` object that is an instance of that `FastAPI` class:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="1 6"
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001_py310.py[ln:1-2]!}
|
||||
|
||||
# SQLModel code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001_py310.py[ln:23]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3 8"
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001.py[ln:1-4]!}
|
||||
|
||||
@ -133,27 +85,14 @@ And then create an `app` object that is an instance of that `FastAPI` class:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Create Database and Tables on `startup`
|
||||
|
||||
@ -161,20 +100,6 @@ We want to make sure that once the app starts running, the function `create_tabl
|
||||
|
||||
This should be called only once at startup, not before every request, so we put it in the function to handle the `"startup"` event:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="6-8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001_py310.py[ln:23-28]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="6-8"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -183,54 +108,24 @@ This should be called only once at startup, not before every request, so we put
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Create Heroes *Path Operation*
|
||||
|
||||
/// info
|
||||
|
||||
If you need a refresher on what a **Path Operation** is (an endpoint with a specific HTTP Operation) and how to work with it in FastAPI, check out the <a href="https://fastapi.tiangolo.com/tutorial/first-steps/" class="external-link" target="_blank">FastAPI First Steps docs</a>.
|
||||
|
||||
///
|
||||
!!! info
|
||||
If you need a refresher on what a **Path Operation** is (an endpoint with a specific HTTP Operation) and how to work with it in FastAPI, check out the <a href="https://fastapi.tiangolo.com/tutorial/first-steps/" class="external-link" target="_blank">FastAPI First Steps docs</a>.
|
||||
|
||||
Let's create the **path operation** code to create a new hero.
|
||||
|
||||
It will be called when a user sends a request with a `POST` **operation** to the `/heroes/` **path**:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="11-12"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001_py310.py[ln:23-37]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="11-12"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -239,37 +134,21 @@ It will be called when a user sends a request with a `POST` **operation** to the
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
</details>
|
||||
|
||||
///
|
||||
!!! info
|
||||
If you need a refresher on some of those concepts, checkout the FastAPI documentation:
|
||||
|
||||
/// info
|
||||
|
||||
If you need a refresher on some of those concepts, checkout the FastAPI documentation:
|
||||
|
||||
* <a href="https://fastapi.tiangolo.com/tutorial/first-steps/" class="external-link" target="_blank">First Steps</a>
|
||||
* <a href="https://fastapi.tiangolo.com/tutorial/path-params/" class="external-link" target="_blank">Path Parameters - Data Validation and Data Conversion</a>
|
||||
* <a href="https://fastapi.tiangolo.com/tutorial/body/" class="external-link" target="_blank">Request Body</a>
|
||||
|
||||
///
|
||||
* <a href="https://fastapi.tiangolo.com/tutorial/first-steps/" class="external-link" target="_blank">First Steps</a>
|
||||
* <a href="https://fastapi.tiangolo.com/tutorial/path-params/" class="external-link" target="_blank">Path Parameters - Data Validation and Data Conversion</a>
|
||||
* <a href="https://fastapi.tiangolo.com/tutorial/body/" class="external-link" target="_blank">Request Body</a>
|
||||
|
||||
## The **SQLModel** Advantage
|
||||
|
||||
@ -283,55 +162,27 @@ And then, because this same **SQLModel** object is not only a **Pydantic** model
|
||||
|
||||
So we can use intuitive standard Python **type annotations**, and we don't have to duplicate a lot of the code for the database models and the API data models. 🎉
|
||||
|
||||
/// tip
|
||||
|
||||
We will improve this further later, but for now, it already shows the power of having **SQLModel** classes be both **SQLAlchemy** models and **Pydantic** models at the same time.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
We will improve this further later, but for now, it already shows the power of having **SQLModel** classes be both **SQLAlchemy** models and **Pydantic** models at the same time.
|
||||
|
||||
## Read Heroes *Path Operation*
|
||||
|
||||
Now let's add another **path operation** to read all the heroes:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="20-24"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001_py310.py[ln:23-44]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="20-24"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001.py[ln:25-46]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This is pretty straightforward.
|
||||
|
||||
@ -375,14 +226,11 @@ $ uvicorn main:app
|
||||
|
||||
</div>
|
||||
|
||||
/// info
|
||||
!!! info
|
||||
The command `uvicorn main:app` refers to:
|
||||
|
||||
The command `uvicorn main:app` refers to:
|
||||
|
||||
* `main`: the file `main.py` (the Python "module").
|
||||
* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
|
||||
|
||||
///
|
||||
* `main`: the file `main.py` (the Python "module").
|
||||
* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
|
||||
|
||||
### Uvicorn `--reload`
|
||||
|
||||
|
||||
@ -14,67 +14,24 @@ It's the same process we did for heroes, with a base model, a **table model**, a
|
||||
|
||||
We have a `TeamBase` **data model**, and from it, we inherit with a `Team` **table model**.
|
||||
|
||||
Then we also inherit from the `TeamBase` for the `TeamCreate` and `TeamPublic` **data models**.
|
||||
Then we also inherit from the `TeamBase` for the `TeamCreate` and `TeamRead` **data models**.
|
||||
|
||||
And we also create a `TeamUpdate` **data model**.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5-7 10-13 16-17 20-21 24-26"
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py310.py[ln:1-26]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="7-9 12-15 18-19 22-23 26-28"
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py39.py[ln:1-28]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="7-9 12-15 18-19 22-23 26-28"
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001.py[ln:1-28]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
We now also have **relationship attributes**. 🎉
|
||||
|
||||
@ -82,33 +39,7 @@ Let's now update the `Hero` models too.
|
||||
|
||||
## Update Hero Models
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3-8 11-14 17-18 21-22 25-29"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py310.py[ln:29-55]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3-8 11-14 17-18 21-22 25-29"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py39.py[ln:31-57]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3-8 11-14 17-18 21-22 25-29"
|
||||
```Python hl_lines="3-8 11-15 17-18 21-22 25-29"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001.py[ln:31-57]!}
|
||||
@ -116,35 +47,14 @@ Let's now update the `Hero` models too.
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
We now have a `team_id` in the hero models.
|
||||
|
||||
@ -156,32 +66,6 @@ And even though the `HeroBase` is *not* a **table model**, we can declare `team_
|
||||
|
||||
Notice that the **relationship attributes**, the ones with `Relationship()`, are **only** in the **table models**, as those are the ones that are handled by **SQLModel** with SQLAlchemy and that can have the automatic fetching of data from the database when we access them.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="11 38"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py310.py[ln:5-55]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="11 38"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py39.py[ln:7-57]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="11 38"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -190,35 +74,14 @@ Notice that the **relationship attributes**, the ones with `Relationship()`, are
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Path Operations for Teams
|
||||
|
||||
@ -226,32 +89,6 @@ Let's now add the **path operations** for teams.
|
||||
|
||||
These are equivalent and very similar to the **path operations** for the **heroes** we had before, so we don't have to go over the details for each one, let's check the code.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3-9 12-20 23-28 31-47 50-57"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py310.py[ln:136-190]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3-9 12-20 23-28 31-47 50-57"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py39.py[ln:138-192]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3-9 12-20 23-28 31-47 50-57"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -260,35 +97,14 @@ These are equivalent and very similar to the **path operations** for the **heroe
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/teams/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Using Relationships Attributes
|
||||
|
||||
|
||||
@ -14,13 +14,14 @@ We will use the application with the hero models, but without team models, and w
|
||||
|
||||
Now we will see how useful it is to have this session dependency. ✨
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/main.py!}
|
||||
```
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## File Structure
|
||||
|
||||
@ -42,12 +43,12 @@ If you haven't done testing in FastAPI applications, first check the <a href="ht
|
||||
|
||||
Then, we can continue here, the first step is to install the dependencies, `requests` and `pytest`.
|
||||
|
||||
Make sure you create a [virtual environment](../../virtual-environments.md){.internal-link target=_blank}, activate it, and then install them, for example with:
|
||||
Make sure you do it in the same [Python environment](../index.md#create-a-python-virtual-environment){.internal-link target=_blank}.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install requests pytest
|
||||
$ python -m pip install requests pytest
|
||||
|
||||
---> 100%
|
||||
```
|
||||
@ -70,11 +71,8 @@ Let's start with a simple test, with just the basic test code we need the check
|
||||
|
||||
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/annotations/en/test_main_001.md!}
|
||||
|
||||
/// tip
|
||||
|
||||
Check out the number bubbles to see what is done by each line of code.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Check out the number bubbles to see what is done by each line of code.
|
||||
|
||||
That's the **core** of the code we need for all the tests later.
|
||||
|
||||
@ -118,11 +116,8 @@ That way we protect the production database and we have better control of the da
|
||||
|
||||
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/annotations/en/test_main_002.md!}
|
||||
|
||||
/// tip
|
||||
|
||||
Check out the number bubbles to see what is done by each line of code.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Check out the number bubbles to see what is done by each line of code.
|
||||
|
||||
## Create the Engine and Session for Testing
|
||||
|
||||
@ -170,8 +165,10 @@ But **it works great for testing**, because it can be quickly created before eac
|
||||
|
||||
And also, because it never has to write anything to a file and it's all just in memory, it will be even faster than normally. 🏎
|
||||
|
||||
/// details | Other alternatives and ideas 👀
|
||||
|
||||
<details>
|
||||
<summary>
|
||||
Other alternatives and ideas 👀
|
||||
</summary>
|
||||
Before arriving at the idea of using an **in-memory database** we could have explored other alternatives and ideas.
|
||||
|
||||
The first is that we are not deleting the file after we finish the test, so the next test could have **leftover data**. So, the right thing would be to delete the file right after finishing the test. 🔥
|
||||
@ -184,7 +181,7 @@ So, if we tried to run the tests at the same time **in parallel** to try to spee
|
||||
|
||||
Of course, we could also fix that, using some **random name** for each testing database file... but in the case of SQLite, we have an even better alternative by just using an **in-memory database**. ✨
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Configure the In-Memory Database
|
||||
|
||||
@ -200,11 +197,8 @@ We just have to change a couple of parameters in the **engine**.
|
||||
|
||||
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/annotations/en/test_main_004.md!}
|
||||
|
||||
/// tip
|
||||
|
||||
Check out the number bubbles to see what is done by each line of code.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Check out the number bubbles to see what is done by each line of code.
|
||||
|
||||
That's it, now the test will run using the **in-memory database**, which will be faster and probably safer.
|
||||
|
||||
@ -220,11 +214,8 @@ Do we really have to duplicate all that for **each test**? No, we can do better!
|
||||
|
||||
We are using **pytest** to run the tests. And pytest also has a very similar concept to the **dependencies in FastAPI**.
|
||||
|
||||
/// info
|
||||
|
||||
In fact, pytest was one of the things that inspired the design of the dependencies in FastAPI.
|
||||
|
||||
///
|
||||
!!! info
|
||||
In fact, pytest was one of the things that inspired the design of the dependencies in FastAPI.
|
||||
|
||||
It's a way for us to declare some **code that should be run before** each test and **provide a value** for the test function (that's pretty much the same as FastAPI dependencies).
|
||||
|
||||
@ -246,11 +237,8 @@ Let's see the first code example with a fixture:
|
||||
|
||||
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/annotations/en/test_main_005.md!}
|
||||
|
||||
/// tip
|
||||
|
||||
Check out the number bubbles to see what is done by each line of code.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Check out the number bubbles to see what is done by each line of code.
|
||||
|
||||
**pytest** fixtures work in a very similar way to FastAPI dependencies, but have some minor differences:
|
||||
|
||||
@ -286,11 +274,8 @@ So, we can create a **client fixture** that will be used in all the tests, and i
|
||||
|
||||
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/annotations/en/test_main_006.md!}
|
||||
|
||||
/// tip
|
||||
|
||||
Check out the number bubbles to see what is done by each line of code.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Check out the number bubbles to see what is done by each line of code.
|
||||
|
||||
Now we have a **client fixture** that, in turn, uses the **session fixture**.
|
||||
|
||||
@ -312,21 +297,19 @@ Let's add some more tests:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/test_main.py!}
|
||||
```
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
It's always **good idea** to not only test the normal case, but also that **invalid data**, **errors**, and **corner cases** are handled correctly.
|
||||
|
||||
It's always **good idea** to not only test the normal case, but also that **invalid data**, **errors**, and **corner cases** are handled correctly.
|
||||
|
||||
That's why we add these two extra tests here.
|
||||
|
||||
///
|
||||
That's why we add these two extra tests here.
|
||||
|
||||
Now, any additional test functions can be as **simple** as the first one, they just have to **declare the `client` parameter** to get the `TestClient` **fixture** with all the database stuff setup. Nice! 😎
|
||||
|
||||
@ -348,13 +331,14 @@ But for the next test function, we will require **both fixtures**, the **client*
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/test_main.py!}
|
||||
```
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
In this test function, we want to check that the *path operation* to **read a list of heroes** actually sends us heroes.
|
||||
|
||||
@ -386,13 +370,14 @@ Using the same ideas, requiring the fixtures, creating data that we need for the
|
||||
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/test_main.py[ln:84-125]!}
|
||||
```
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/test_main.py!}
|
||||
```
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Run the Tests
|
||||
|
||||
|
||||
@ -1,465 +0,0 @@
|
||||
# Update with Extra Data (Hashed Passwords) with FastAPI
|
||||
|
||||
In the previous chapter I explained to you how to update data in the database from input data coming from a **FastAPI** *path operation*.
|
||||
|
||||
Now I'll explain to you how to add **extra data**, additional to the input data, when updating or creating a model object.
|
||||
|
||||
This is particularly useful when you need to **generate some data** in your code that is **not coming from the client**, but you need to store it in the database. For example, to store a **hashed password**.
|
||||
|
||||
## Password Hashing
|
||||
|
||||
Let's imagine that each hero in our system also has a **password**.
|
||||
|
||||
We should never store the password in plain text in the database, we should only stored a **hashed version** of it.
|
||||
|
||||
"**Hashing**" means converting some content (a password in this case) into a sequence of bytes (just a string) that looks like gibberish.
|
||||
|
||||
Whenever you pass exactly the same content (exactly the same password) you get exactly the same gibberish.
|
||||
|
||||
But you **cannot convert** from the gibberish **back to the password**.
|
||||
|
||||
### Why use Password Hashing
|
||||
|
||||
If your database is stolen, the thief won't have your users' **plaintext passwords**, only the hashes.
|
||||
|
||||
So, the thief won't be able to try to use that password in another system (as many users use the same password everywhere, this would be dangerous).
|
||||
|
||||
/// tip
|
||||
|
||||
You could use <a href="https://passlib.readthedocs.io/en/stable/" class="external-link" target="_blank">passlib</a> to hash passwords.
|
||||
|
||||
In this example we will use a fake hashing function to focus on the data changes. 🤡
|
||||
|
||||
///
|
||||
|
||||
## Update Models with Extra Data
|
||||
|
||||
The `Hero` table model will now store a new field `hashed_password`.
|
||||
|
||||
And the data models for `HeroCreate` and `HeroUpdate` will also have a new field `password` that will contain the plain text password sent by clients.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="11 15 26"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py310.py[ln:5-28]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="11 15 26"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py39.py[ln:7-30]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="11 15 26"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002.py[ln:7-30]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
|
||||
When a client is creating a new hero, they will send the `password` in the request body.
|
||||
|
||||
And when they are updating a hero, they could also send the `password` in the request body to update it.
|
||||
|
||||
## Hash the Password
|
||||
|
||||
The app will receive the data from the client using the `HeroCreate` model.
|
||||
|
||||
This contains the `password` field with the plain text password, and we cannot use that one. So we need to generate a hash from it.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="11"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py310.py[ln:42-44]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py310.py[ln:55-57]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="11"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py39.py[ln:44-46]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py39.py[ln:57-59]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="11"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002.py[ln:44-46]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002.py[ln:57-59]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
|
||||
## Create an Object with Extra Data
|
||||
|
||||
Now we need to create the database hero.
|
||||
|
||||
In previous examples, we have used something like:
|
||||
|
||||
```Python
|
||||
db_hero = Hero.model_validate(hero)
|
||||
```
|
||||
|
||||
This creates a `Hero` (which is a *table model*) object from the `HeroCreate` (which is a *data model*) object that we received in the request.
|
||||
|
||||
And this is all good... but as `Hero` doesn't have a field `password`, it won't be extracted from the object `HeroCreate` that has it.
|
||||
|
||||
`Hero` actually has a `hashed_password`, but we are not providing it. We need a way to provide it...
|
||||
|
||||
### Dictionary Update
|
||||
|
||||
Let's pause for a second to check this, when working with dictionaries, there's a way to `update` a dictionary with extra data from another dictionary, something like this:
|
||||
|
||||
```Python hl_lines="14"
|
||||
db_user_dict = {
|
||||
"name": "Deadpond",
|
||||
"secret_name": "Dive Wilson",
|
||||
"age": None,
|
||||
}
|
||||
|
||||
hashed_password = "fakehashedpassword"
|
||||
|
||||
extra_data = {
|
||||
"hashed_password": hashed_password,
|
||||
"age": 32,
|
||||
}
|
||||
|
||||
db_user_dict.update(extra_data)
|
||||
|
||||
print(db_user_dict)
|
||||
|
||||
# {
|
||||
# "name": "Deadpond",
|
||||
# "secret_name": "Dive Wilson",
|
||||
# "age": 32,
|
||||
# "hashed_password": "fakehashedpassword",
|
||||
# }
|
||||
```
|
||||
|
||||
This `update` method allows us to add and override things in the original dictionary with the data from another dictionary.
|
||||
|
||||
So now, `db_user_dict` has the updated `age` field with `32` instead of `None` and more importantly, **it has the new `hashed_password` field**.
|
||||
|
||||
### Create a Model Object with Extra Data
|
||||
|
||||
Similar to how dictionaries have an `update` method, **SQLModel** models have a parameter `update` in `Hero.model_validate()` that takes a dictionary with extra data, or data that should take precedence:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py310.py[ln:55-64]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py39.py[ln:57-66]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002.py[ln:57-66]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
|
||||
Now, `db_hero` (which is a *table model* `Hero`) will extract its values from `hero` (which is a *data model* `HeroCreate`), and then it will **`update`** its values with the extra data from the dictionary `extra_data`.
|
||||
|
||||
It will only take the fields defined in `Hero`, so **it will not take the `password`** from `HeroCreate`. And it will also **take its values** from the **dictionary passed to the `update`** parameter, in this case, the `hashed_password`.
|
||||
|
||||
If there's a field in both `hero` and the `extra_data`, **the value from the `extra_data` passed to `update` will take precedence**.
|
||||
|
||||
## Update with Extra Data
|
||||
|
||||
Now let's say we want to **update a hero** that already exists in the database.
|
||||
|
||||
The same way as before, to avoid removing existing data, we will use `exclude_unset=True` when calling `hero.model_dump()`, to get a dictionary with only the data sent by the client.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py310.py[ln:83-89]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py39.py[ln:85-91]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002.py[ln:85-91]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
|
||||
Now, this `hero_data` dictionary could contain a `password`. We need to check it, and if it's there, we need to generate the `hashed_password`.
|
||||
|
||||
Then we can put that `hashed_password` in a dictionary.
|
||||
|
||||
And then we can update the `db_hero` object using the method `db_hero.sqlmodel_update()`.
|
||||
|
||||
It takes a model object or dictionary with the data to update the object and also an **additional `update` argument** with extra data.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="15"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py310.py[ln:83-99]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="15"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py39.py[ln:85-101]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="15"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002.py[ln:85-101]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
|
||||
/// tip
|
||||
|
||||
The method `db_hero.sqlmodel_update()` was added in SQLModel 0.0.16. 😎
|
||||
|
||||
///
|
||||
|
||||
## Recap
|
||||
|
||||
You can use the `update` parameter in `Hero.model_validate()` to provide extra data when creating a new object and `Hero.sqlmodel_update()` to provide extra data when updating an existing object. 🤓
|
||||
@ -12,42 +12,13 @@ So, we need to have all those fields **marked as optional**.
|
||||
|
||||
And because the `HeroBase` has some of them as *required* and not optional, we will need to **create a new model**.
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
Here is one of those cases where it probably makes sense to use an **independent model** instead of trying to come up with a complex tree of models inheriting from each other.
|
||||
|
||||
Here is one of those cases where it probably makes sense to use an **independent model** instead of trying to come up with a complex tree of models inheriting from each other.
|
||||
|
||||
Because each field is **actually different** (we just change it to `Optional`, but that's already making it different), it makes sense to have them in their own model.
|
||||
|
||||
///
|
||||
Because each field is **actually different** (we just change it to `Optional`, but that's already making it different), it makes sense to have them in their own model.
|
||||
|
||||
So, let's create this new `HeroUpdate` model:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="21-24"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py310.py[ln:5-26]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="21-24"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py39.py[ln:7-28]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="21-24"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -56,35 +27,14 @@ So, let's create this new `HeroUpdate` model:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This is almost the same as `HeroBase`, but all the fields are optional, so we can't simply inherit from `HeroBase`.
|
||||
|
||||
@ -94,32 +44,6 @@ Now let's use this model in the *path operation* to update a hero.
|
||||
|
||||
We will use a `PATCH` HTTP operation. This is used to **partially update data**, which is what we are doing.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3-4"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py310.py[ln:74-89]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3-4"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py39.py[ln:76-91]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3-4"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -128,35 +52,14 @@ We will use a `PATCH` HTTP operation. This is used to **partially update data**,
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
We also read the `hero_id` from the *path parameter* and the request body, a `HeroUpdate`.
|
||||
|
||||
@ -166,32 +69,6 @@ We take a `hero_id` with the **ID** of the hero **we want to update**.
|
||||
|
||||
So, we need to read the hero from the database, with the **same logic** we used to **read a single hero**, checking if it exists, possibly raising an error for the client if it doesn't exist, etc.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="6-8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py310.py[ln:74-89]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="6-8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py39.py[ln:76-91]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="6-8"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -200,41 +77,20 @@ So, we need to read the hero from the database, with the **same logic** we used
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
### Get the New Data
|
||||
|
||||
The `HeroUpdate` model has all the fields with **default values**, because they all have defaults, they are all optional, which is what we want.
|
||||
|
||||
But that also means that if we just call `hero.model_dump()` we will get a dictionary that could potentially have several or all of those values with their defaults, for example:
|
||||
But that also means that if we just call `hero.dict()` we will get a dictionary that could potentially have several or all of those values with their defaults, for example:
|
||||
|
||||
```Python
|
||||
{
|
||||
@ -246,7 +102,7 @@ But that also means that if we just call `hero.model_dump()` we will get a dicti
|
||||
|
||||
And then, if we update the hero in the database with this data, we would be removing any existing values, and that's probably **not what the client intended**.
|
||||
|
||||
But fortunately Pydantic models (and so SQLModel models) have a parameter we can pass to the `.model_dump()` method for that: `exclude_unset=True`.
|
||||
But fortunately Pydantic models (and so SQLModel models) have a parameter we can pass to the `.dict()` method for that: `exclude_unset=True`.
|
||||
|
||||
This tells Pydantic to **not include** the values that were **not sent** by the client. Saying it another way, it would **only** include the values that were **sent by the client**.
|
||||
|
||||
@ -256,7 +112,7 @@ So, if the client sent a JSON with no values:
|
||||
{}
|
||||
```
|
||||
|
||||
Then the dictionary we would get in Python using `hero.model_dump(exclude_unset=True)` would be:
|
||||
Then the dictionary we would get in Python using `hero.dict(exclude_unset=True)` would be:
|
||||
|
||||
```Python
|
||||
{}
|
||||
@ -270,7 +126,7 @@ But if the client sent a JSON with:
|
||||
}
|
||||
```
|
||||
|
||||
Then the dictionary we would get in Python using `hero.model_dump(exclude_unset=True)` would be:
|
||||
Then the dictionary we would get in Python using `hero.dict(exclude_unset=True)` would be:
|
||||
|
||||
```Python
|
||||
{
|
||||
@ -280,32 +136,6 @@ Then the dictionary we would get in Python using `hero.model_dump(exclude_unset=
|
||||
|
||||
Then we use that to get the data that was actually sent by the client:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py310.py[ln:74-89]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py39.py[ln:76-91]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -314,71 +144,20 @@ Then we use that to get the data that was actually sent by the client:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
|
||||
/// tip
|
||||
Before SQLModel 0.0.14, the method was called `hero.dict(exclude_unset=True)`, but it was renamed to `hero.model_dump(exclude_unset=True)` to be consistent with Pydantic v2.
|
||||
///
|
||||
</details>
|
||||
|
||||
## Update the Hero in the Database
|
||||
|
||||
Now that we have a **dictionary with the data sent by the client**, we can use the method `db_hero.sqlmodel_update()` to update the object `db_hero`.
|
||||
Now that we have a **dictionary with the data sent by the client**, we can iterate for each one of the keys and the values, and then we set them in the database hero model `db_hero` using `setattr()`.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="10"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py310.py[ln:74-89]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="10"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py39.py[ln:76-91]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="10"
|
||||
```Python hl_lines="10-11"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001.py[ln:76-91]!}
|
||||
@ -386,47 +165,28 @@ Now that we have a **dictionary with the data sent by the client**, we can use t
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/fastapi/update/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
</details>
|
||||
|
||||
///
|
||||
If you are not familiar with that `setattr()`, it takes an object, like the `db_hero`, then an attribute name (`key`), that in our case could be `"name"`, and a value (`value`). And then it **sets the attribute with that name to the value**.
|
||||
|
||||
/// tip
|
||||
So, if `key` was `"name"` and `value` was `"Deadpuddle"`, then this code:
|
||||
|
||||
The method `db_hero.sqlmodel_update()` was added in SQLModel 0.0.16. 🤓
|
||||
```Python
|
||||
setattr(db_hero, key, value)
|
||||
```
|
||||
|
||||
Before that, you would need to manually get the values and set them using `setattr()`.
|
||||
...would be more or less equivalent to:
|
||||
|
||||
///
|
||||
|
||||
The method `db_hero.sqlmodel_update()` takes an argument with another model object or a dictionary.
|
||||
|
||||
For each of the fields in the **original** model object (`db_hero` in this example), it checks if the field is available in the **argument** (`hero_data` in this example) and then updates it with the provided value.
|
||||
```Python
|
||||
db_hero.name = "Deadpuddle"
|
||||
```
|
||||
|
||||
## Remove Fields
|
||||
|
||||
@ -450,7 +210,7 @@ So, if the client wanted to intentionally remove the `age` of a hero, they could
|
||||
}
|
||||
```
|
||||
|
||||
And when getting the data with `hero.model_dump(exclude_unset=True)`, we would get:
|
||||
And when getting the data with `hero.dict(exclude_unset=True)`, we would get:
|
||||
|
||||
```Python
|
||||
{
|
||||
@ -468,4 +228,4 @@ These are some of the advantages of Pydantic, that we can use with SQLModel.
|
||||
|
||||
## Recap
|
||||
|
||||
Using `.model_dump(exclude_unset=True)` in SQLModel models (and Pydantic models) we can easily update data **correctly**, even in the **edge cases**. 😎
|
||||
Using `.dict(exclude_unset=True)` in SQLModel models (and Pydantic models) we can easily update data **correctly**, even in the **edge cases**. 😎
|
||||
|
||||
@ -1,6 +1,4 @@
|
||||
# Tutorial - User Guide
|
||||
|
||||
In this tutorial you will learn how to use **SQLModel**.
|
||||
# Intro, Installation, and First Steps
|
||||
|
||||
## Type hints
|
||||
|
||||
@ -31,3 +29,187 @@ Using it in your editor is what really shows you the benefits of **SQLModel**, s
|
||||
Running the examples is what will really help you understand what is going on.
|
||||
|
||||
You can learn a lot more by running some examples and playing around with them than by reading all the docs here.
|
||||
|
||||
## Create a Project
|
||||
|
||||
Please go ahead and create a directory for the project we will work on on this tutorial.
|
||||
|
||||
What I normally do is that I create a directory named `code` inside my home/user directory.
|
||||
|
||||
And inside of that I create one directory per project.
|
||||
|
||||
So, for example:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Go to the home directory
|
||||
$ cd
|
||||
// Create a directory for all your code projects
|
||||
$ mkdir code
|
||||
// Enter into that code directory
|
||||
$ cd code
|
||||
// Create a directory for this project
|
||||
$ mkdir sqlmodel-tutorial
|
||||
// Enter into that directory
|
||||
$ cd sqlmodel-tutorial
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
!!! tip
|
||||
Make sure you don't name it also `sqlmodel`, so that you don't end up overriding the name of the package.
|
||||
|
||||
### Make sure you have Python
|
||||
|
||||
Make sure you have an officially supported version of Python.
|
||||
|
||||
You can check which version you have with:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ python3 --version
|
||||
Python 3.11
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
There's a chance that you have multiple Python versions installed.
|
||||
|
||||
You might want to try with the specific versions, for example with:
|
||||
|
||||
* `python3.10`
|
||||
* `python3.9`
|
||||
* `python3.8`
|
||||
|
||||
The code would look like this:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Let's check with just python3
|
||||
$ python3 --version
|
||||
// This is too old! 😱
|
||||
Python 3.5.6
|
||||
// Let's see if python3.10 is available
|
||||
$ python3.10 --version
|
||||
// Oh, no, this one is not available 😔
|
||||
command not found: python3.10
|
||||
$ python3.9 --version
|
||||
// Nice! This works 🎉
|
||||
Python 3.9.0
|
||||
// In this case, we would continue using python3.9 instead of python3
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
If you have different versions and `python3` is not the latest, make sure you use the latest version you have available. For example `python3.9`.
|
||||
|
||||
If you don't have a valid Python version installed, go and install that first.
|
||||
|
||||
### Create a Python virtual environment
|
||||
|
||||
When writing Python code, you should **always** use virtual environments in one way or another.
|
||||
|
||||
If you don't know what that is, you can read the <a href="https://docs.python.org/3/tutorial/venv.html" class="external-link" target="_blank">official tutorial for virtual environments</a>, it's quite simple.
|
||||
|
||||
In very short, a virtual environment is a small directory that contains a copy of Python and all the libraries you need to run your code.
|
||||
|
||||
And when you "activate" it, any package that you install, for example with `pip`, will be installed in that virtual environment.
|
||||
|
||||
!!! tip
|
||||
There are other tools to manage virtual environments, like <a href="https://python-poetry.org/" class="external-link" target="_blank">Poetry</a>.
|
||||
|
||||
And there are alternatives that are particularly useful for deployment like <a href="https://docs.docker.com/get-started/" class="external-link" target="_blank">Docker</a> and other types of containers. In this case, the "virtual environment" is not just the Python standard files and the installed packages, but the whole system.
|
||||
|
||||
Go ahead and create a Python virtual environment for this project. And make sure to also upgrade `pip`.
|
||||
|
||||
Here are the commands you could use:
|
||||
|
||||
=== "Linux, macOS, Linux in Windows"
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Remember that you might need to use python3.9 or similar 💡
|
||||
// Create the virtual environment using the module "venv"
|
||||
$ python3 -m venv env
|
||||
// ...here it creates the virtual environment in the directory "env"
|
||||
// Activate the virtual environment
|
||||
$ source ./env/bin/activate
|
||||
// Verify that the virtual environment is active
|
||||
# (env) $$ which python
|
||||
// The important part is that it is inside the project directory, at "code/sqlmodel-tutorial/env/bin/python"
|
||||
/home/leela/code/sqlmodel-tutorial/env/bin/python
|
||||
// Use the module "pip" to install and upgrade the package "pip" 🤯
|
||||
# (env) $$ python -m pip install --upgrade pip
|
||||
---> 100%
|
||||
Successfully installed pip
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
=== "Windows PowerShell"
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Create the virtual environment using the module "venv"
|
||||
# >$ python3 -m venv env
|
||||
// ...here it creates the virtual environment in the directory "env"
|
||||
// Activate the virtual environment
|
||||
# >$ .\env\Scripts\Activate.ps1
|
||||
// Verify that the virtual environment is active
|
||||
# (env) >$ Get-Command python
|
||||
// The important part is that it is inside the project directory, at "code\sqlmodel-tutorial\env\python.exe"
|
||||
CommandType Name Version Source
|
||||
----------- ---- ------- ------
|
||||
Application python 0.0.0.0 C:\Users\leela\code\sqlmodel-tutorial\env\python.exe
|
||||
// Use the module "pip" to install and upgrade the package "pip" 🤯
|
||||
# (env) >$ python3 -m pip install --upgrade pip
|
||||
---> 100%
|
||||
Successfully installed pip
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## Install **SQLModel**
|
||||
|
||||
Now, after making sure we are inside of a virtual environment in some way, we can install **SQLModel**:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
# (env) $$ python -m pip install sqlmodel
|
||||
---> 100%
|
||||
Successfully installed sqlmodel pydantic sqlalchemy
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
As **SQLModel** is built on top of <a href="https://www.sqlalchemy.org/" class="external-link" target="_blank">SQLAlchemy</a> and <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>, when you install `sqlmodel` they will also be automatically installed.
|
||||
|
||||
## Install DB Browser for SQLite
|
||||
|
||||
Remember that [SQLite is a simple database in a single file](../databases.md#a-single-file-database){.internal-link target=_blank}?
|
||||
|
||||
For most of the tutorial I'll use SQLite for the examples.
|
||||
|
||||
Python has integrated support for SQLite, it is a single file read and processed from Python. And it doesn't need an [External Database Server](../databases.md#a-server-database){.internal-link target=_blank}, so it will be perfect for learning.
|
||||
|
||||
In fact, SQLite is perfectly capable of handling quite big applications. At some point you might want to migrate to a server-based database like <a href="https://www.postgresql.org/" class="external-link" target="_blank">PostgreSQL</a> (which is also free). But for now we'll stick to SQLite.
|
||||
|
||||
Through the tutorial I will show you SQL fragments, and Python examples. And I hope (and expect 🧐) you to actually run them, and verify that the database is working as expected and showing you the same data.
|
||||
|
||||
To be able to explore the SQLite file yourself, independent of Python code (and probably at the same time), I recommend you use <a href="https://sqlitebrowser.org/" class="external-link" target="_blank">DB Browser for SQLite</a>.
|
||||
|
||||
It's a great and simple program to interact with SQLite databases (SQLite files) in a nice user interface.
|
||||
|
||||
<img src="https://sqlitebrowser.org/images/screenshot.png">
|
||||
|
||||
Go ahead and <a href="https://sqlitebrowser.org/" class="external-link" target="_blank">Install DB Browser for SQLite</a>, it's free.
|
||||
|
||||
## Next Steps
|
||||
|
||||
Okay, let's get going! On the [next section](create-db-and-table-with-db-browser.md) we'll start creating a database. 🚀
|
||||
|
||||
@ -20,25 +20,14 @@ Are you already a **SQL expert** and don't have time for all my explanations?
|
||||
|
||||
Fine, in that case, you can **sneak peek** the final code to create indexes here.
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/indexes/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python
|
||||
```Python hl_lines="8 10"
|
||||
{!./docs_src/tutorial/indexes/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
..but if you are not an expert, **continue reading**, this will probably be useful. 🤓
|
||||
|
||||
@ -84,15 +73,12 @@ You repeat this process **a few more times**, and you finally arrive at the lett
|
||||
|
||||
You had to open the dictionary a few times, maybe **5 or 10**. That's actually **very little work** compared to what it could have been.
|
||||
|
||||
/// note | Technical Details
|
||||
!!! note "Technical Details"
|
||||
Do you like **fancy words**? Cool! Programmers tend to like fancy words. 😅
|
||||
|
||||
Do you like **fancy words**? Cool! Programmers tend to like fancy words. 😅
|
||||
That <abbr title="a recipe, a sequence of predefined steps that achieve a result">algorithm</abbr> I showed you above is called **Binary Search**.
|
||||
|
||||
That <abbr title="a recipe, a sequence of predefined steps that achieve a result">algorithm</abbr> I showed you above is called **Binary Search**.
|
||||
|
||||
It's called that because you **search** something by splitting the dictionary (or any ordered list of things) in **two** ("binary" means "two") parts. And you do that process multiple times until you find what you want.
|
||||
|
||||
///
|
||||
It's called like that because you **search** something by splitting the dictionary (or any ordered list of things) in **two** ("binary" means "two") parts. And you do that process multiple times until you find what you want.
|
||||
|
||||
### An Index and a Novel
|
||||
|
||||
@ -275,99 +261,46 @@ The change in code is underwhelming, it's very simple. 😆
|
||||
|
||||
Here's the `Hero` model we had before:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="6"
|
||||
{!./docs_src/tutorial/where/tutorial001_py310.py[ln:1-8]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!./docs_src/tutorial/where/tutorial001.py[ln:1-10]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Let's now update it to tell **SQLModel** to create an index for the `name` field when creating the table:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="6"
|
||||
{!./docs_src/tutorial/indexes/tutorial001_py310.py[ln:1-8]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!./docs_src/tutorial/indexes/tutorial001.py[ln:1-10]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/indexes/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/indexes/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
We use the same `Field()` again as we did before, and set `index=True`. That's it! 🚀
|
||||
|
||||
Notice that we didn't set an argument of `default=None` or anything similar. This means that **SQLModel** (thanks to Pydantic) will keep it as a **required** field.
|
||||
|
||||
/// info
|
||||
!!! info
|
||||
SQLModel (actually SQLAlchemy) will **automatically generate the index name** for you.
|
||||
|
||||
SQLModel (actually SQLAlchemy) will **automatically generate the index name** for you.
|
||||
|
||||
In this case the generated name would be `ix_hero_name`.
|
||||
|
||||
///
|
||||
In this case the generated name would be `ix_hero_name`.
|
||||
|
||||
## Query Data
|
||||
|
||||
@ -377,20 +310,6 @@ The SQL database will figure it out **automatically**. ✨
|
||||
|
||||
This is great because it means that indexes are very **simple to use**. But it might also feel counterintuitive at first, as you are **not doing anything** explicitly in the code to make it obvious that the index is useful, it all happens in the database behind the scenes.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/indexes/tutorial001_py310.py[ln:34-39]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -399,27 +318,14 @@ This is great because it means that indexes are very **simple to use**. But it m
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/indexes/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/indexes/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This is exactly the same code as we had before, but now the database will **use the index** underneath.
|
||||
|
||||
@ -462,45 +368,20 @@ secret_name='Dive Wilson' age=None id=1 name='Deadpond'
|
||||
|
||||
We are going to query the `hero` table doing comparisons on the `age` field too, so we should **define an index** for that one as well:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="8"
|
||||
{!./docs_src/tutorial/indexes/tutorial002_py310.py[ln:1-8]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="10"
|
||||
{!./docs_src/tutorial/indexes/tutorial002.py[ln:1-10]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/indexes/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/indexes/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
In this case, we want the default value of `age` to continue being `None`, so we set `default=None` when using `Field()`.
|
||||
|
||||
|
||||
@ -25,22 +25,6 @@ We will continue from where we left of in the last chapter.
|
||||
|
||||
This is the code we had to create the database and table, nothing new here:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```{.python .annotate hl_lines="20" }
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial003_py310.py[ln:1-18]!}
|
||||
|
||||
# More code here later 👈
|
||||
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial003_py310.py[ln:21-22]!}
|
||||
```
|
||||
|
||||
{!./docs_src/tutorial/create_db_and_table/annotations/en/tutorial003.md!}
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```{.python .annotate hl_lines="22" }
|
||||
{!./docs_src/tutorial/create_db_and_table/tutorial003.py[ln:1-20]!}
|
||||
|
||||
@ -51,8 +35,6 @@ This is the code we had to create the database and table, nothing new here:
|
||||
|
||||
{!./docs_src/tutorial/create_db_and_table/annotations/en/tutorial003.md!}
|
||||
|
||||
////
|
||||
|
||||
Now that we can create the database and the table, we will continue from this point and add more code on the same file to create the data.
|
||||
|
||||
## Create Data with SQL
|
||||
@ -88,11 +70,8 @@ You can try that SQL statement in **DB Explorer for SQLite**.
|
||||
|
||||
Make sure to open the same database we already created by clicking <kbd>Open Database</kbd> and selecting the same `database.db` file.
|
||||
|
||||
/// tip
|
||||
|
||||
If you don't have that `database.db` file with the table `hero`, you can re-create it by running the Python program at the top. 👆
|
||||
|
||||
///
|
||||
!!! tip
|
||||
If you don't have that `database.db` file with the table `hero`, you can re-create it by running the Python program at the top. 👆
|
||||
|
||||
Then go to the <kbd>Execute SQL</kbd> tab and copy the SQL from above.
|
||||
|
||||
@ -145,20 +124,6 @@ So, the first step is to simply create an instance of `Hero`.
|
||||
|
||||
We'll create 3 right away, for the 3 heroes:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/insert/tutorial002_py310.py[ln:21-24]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -167,35 +132,19 @@ We'll create 3 right away, for the 3 heroes:
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
</details>
|
||||
|
||||
///
|
||||
!!! tip
|
||||
The code above in this file (the omitted code) is just the same code that you see at the top of this chapter.
|
||||
|
||||
/// tip
|
||||
|
||||
The code above in this file (the omitted code) is just the same code that you see at the top of this chapter.
|
||||
|
||||
The same code we used before to create the `Hero` model.
|
||||
|
||||
///
|
||||
The same code we used before to create the `Hero` model.
|
||||
|
||||
We are putting that in a function `create_heroes()`, to call it later once we finish it.
|
||||
|
||||
@ -219,62 +168,23 @@ We would re-use the same **engine** in all the code, everywhere in the applicati
|
||||
|
||||
The first step is to import the `Session` class:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!./docs_src/tutorial/insert/tutorial001_py310.py[ln:1]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!./docs_src/tutorial/insert/tutorial001.py[ln:1-3]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Then we can create a new session:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/insert/tutorial001_py310.py[ln:21-26]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -283,53 +193,24 @@ Then we can create a new session:
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
The new `Session` takes an `engine` as a parameter. And it will use the **engine** underneath.
|
||||
|
||||
/// tip
|
||||
|
||||
We will see a better way to create a **session** using a `with` block later.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
We will see a better way to create a **session** using a `with` block later.
|
||||
|
||||
## Add Model Instances to the Session
|
||||
|
||||
Now that we have some hero model instances (some objects in memory) and a **session**, the next step is to add them to the session:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="9-11"
|
||||
# Code above omitted 👆
|
||||
{!./docs_src/tutorial/insert/tutorial001_py310.py[ln:21-30]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="9-11"
|
||||
# Code above omitted 👆
|
||||
{!./docs_src/tutorial/insert/tutorial001.py[ln:23-32]!}
|
||||
@ -337,27 +218,14 @@ Now that we have some hero model instances (some objects in memory) and a **sess
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
By this point, our heroes are *not* stored in the database yet.
|
||||
|
||||
@ -369,31 +237,15 @@ And once we are ready, we can **commit** those changes, and then the **session**
|
||||
|
||||
This makes the interactions with the database more efficient (plus some extra benefits).
|
||||
|
||||
/// info | Technical Details
|
||||
!!! info "Technical Details"
|
||||
The session will create a new transaction and execute all the SQL code in that transaction.
|
||||
|
||||
The session will create a new transaction and execute all the SQL code in that transaction.
|
||||
|
||||
This ensures that the data is saved in a single batch, and that it will all succeed or all fail, but it won't leave the database in a broken state.
|
||||
|
||||
///
|
||||
This ensures that the data is saved in a single batch, and that it will all succeed or all fail, but it won't leave the database in a broken state.
|
||||
|
||||
## Commit the Session Changes
|
||||
|
||||
Now that we have the heroes in the **session** and that we are ready to save all that to the database, we can **commit** the changes:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="13"
|
||||
# Code above omitted 👆
|
||||
{!./docs_src/tutorial/insert/tutorial001_py310.py[ln:21-32]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="13"
|
||||
# Code above omitted 👆
|
||||
{!./docs_src/tutorial/insert/tutorial001.py[ln:23-34]!}
|
||||
@ -401,27 +253,14 @@ Now that we have the heroes in the **session** and that we are ready to save all
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Once this line is executed, the **session** will use the **engine** to save all the data in the database by sending the corresponding SQL.
|
||||
|
||||
@ -448,19 +287,6 @@ if __name__ == "__main__":
|
||||
|
||||
But to keep things a bit more organized, let's instead create a new function `main()` that will contain all the code that should be executed when called as an independent script, and we can put there the previous function `create_db_and_tables()`, and add the new function `create_heroes()`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="2 4"
|
||||
# Code above omitted 👆
|
||||
{!./docs_src/tutorial/insert/tutorial002_py310.py[ln:34-36]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="2 4"
|
||||
# Code above omitted 👆
|
||||
{!./docs_src/tutorial/insert/tutorial002.py[ln:36-38]!}
|
||||
@ -468,67 +294,30 @@ But to keep things a bit more organized, let's instead create a new function `ma
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
And then we can call that single `main()` function from that main block:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
{!./docs_src/tutorial/insert/tutorial002_py310.py[ln:34-40]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
{!./docs_src/tutorial/insert/tutorial002.py[ln:36-42]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
By having everything that should happen when called as a script in a single function, we can easily add more code later on.
|
||||
|
||||
@ -583,20 +372,6 @@ The **session** holds some resources, like connections from the engine.
|
||||
|
||||
So once we are done with the session, we should **close** it to make it release those resources and finish its cleanup:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="16"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/insert/tutorial001_py310.py[ln:21-34]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="16"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -605,27 +380,14 @@ So once we are done with the session, we should **close** it to make it release
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
But what happens if we forget to close the session?
|
||||
|
||||
@ -639,43 +401,19 @@ It's good to know how the `Session` works and how to create and close it manuall
|
||||
|
||||
But there's a better way to handle the session, using a `with` block:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="7-12"
|
||||
# Code above omitted 👆
|
||||
{!./docs_src/tutorial/insert/tutorial002_py310.py[ln:21-31]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="7-12"
|
||||
# Code above omitted 👆
|
||||
{!./docs_src/tutorial/insert/tutorial002.py[ln:23-33]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This is the same as creating the session manually and then manually closing it. But here, using a `with` block, it will be automatically created when **starting** the `with` block and assigned to the variable `session`, and it will be automatically closed after the `with` block is **finished**.
|
||||
|
||||
@ -689,31 +427,14 @@ You already know all the first part creating the `Hero` model class, the **engin
|
||||
|
||||
Let's focus on the new code:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```{.python .annotate }
|
||||
{!./docs_src/tutorial/insert/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
{!./docs_src/tutorial/insert/annotations/en/tutorial003.md!}
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```{.python .annotate }
|
||||
{!./docs_src/tutorial/insert/tutorial003.py!}
|
||||
```
|
||||
|
||||
{!./docs_src/tutorial/insert/annotations/en/tutorial003.md!}
|
||||
|
||||
////
|
||||
|
||||
/// tip
|
||||
|
||||
Review what each line does by clicking each number bubble in the code. 👆
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Review what each line does by clicking each number bubble in the code. 👆
|
||||
|
||||
You can now put it in a `app.py` file and run it with Python. And you will see an output like the one shown above.
|
||||
|
||||
|
||||
@ -14,20 +14,6 @@ We will continue with the same code as before, but we'll modify it a little the
|
||||
|
||||
Again, we will create several heroes to have some data to select from:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="4-10"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/offset_and_limit/tutorial001_py310.py[ln:21-39]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="4-10"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -36,46 +22,19 @@ Again, we will create several heroes to have some data to select from:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/offset_and_limit/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/offset_and_limit/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Review Select All
|
||||
|
||||
This is the code we had to select all the heroes in the `select()` examples:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3-8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/select/tutorial003_py310.py[ln:34-39]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3-8"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -84,27 +43,14 @@ This is the code we had to select all the heroes in the `select()` examples:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial003.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
But this would get us **all** the heroes at the same time, in a database that could have thousands, that could be problematic.
|
||||
|
||||
@ -112,20 +58,6 @@ But this would get us **all** the heroes at the same time, in a database that co
|
||||
|
||||
We currently have 7 heroes in the database. But we could as well have thousands, so let's limit the results to get only the first 3:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/offset_and_limit/tutorial001_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -134,27 +66,14 @@ We currently have 7 heroes in the database. But we could as well have thousands,
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/offset_and_limit/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/offset_and_limit/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
The special **select** object we get from `select()` also has a method `.limit()` that we can use to limit the results to a certain number.
|
||||
|
||||
@ -191,11 +110,8 @@ INFO Engine [no key 0.00014s] (3, 0)
|
||||
|
||||
Great! We got only 3 heroes as we wanted.
|
||||
|
||||
/// tip
|
||||
|
||||
We will check out that SQL code more in a bit.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
We will check out that SQL code more in a bit.
|
||||
|
||||
## Select with Offset and Limit
|
||||
|
||||
@ -203,13 +119,10 @@ Now we can limit the results to get only the first 3.
|
||||
|
||||
But imagine we are in a user interface showing the results in batches of 3 heroes at a time.
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
This is commonly called "pagination". Because the user interface would normally show a "page" of a predefined number of heroes at a time.
|
||||
|
||||
This is commonly called "pagination". Because the user interface would normally show a "page" of a predefined number of heroes at a time.
|
||||
|
||||
And then you can interact with the user interface to get the next page, and so on.
|
||||
|
||||
///
|
||||
And then you can interact with the user interface to get the next page, and so on.
|
||||
|
||||
How do we get the next 3?
|
||||
|
||||
@ -217,20 +130,6 @@ How do we get the next 3?
|
||||
|
||||
We can use `.offset()`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/offset_and_limit/tutorial002_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -239,27 +138,14 @@ We can use `.offset()`:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/offset_and_limit/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/offset_and_limit/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
The way this works is that the special **select** object we get from `select()` has methods like `.where()`, `.offset()` and `.limit()`.
|
||||
|
||||
@ -298,20 +184,6 @@ INFO Engine [no key 0.00020s] (3, 3)
|
||||
|
||||
Then to get the next batch of 3 rows we would offset all the ones we already saw, the first 6:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/offset_and_limit/tutorial003_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -320,27 +192,14 @@ Then to get the next batch of 3 rows we would offset all the ones we already saw
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/offset_and_limit/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/offset_and_limit/tutorial003.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
The database right now has **only 7 rows**, so this query can only get 1 row.
|
||||
|
||||
@ -395,20 +254,6 @@ If you try that in **DB Browser for SQLite**, you will get the same result:
|
||||
|
||||
Of course, you can also combine `.limit()` and `.offset()` with `.where()` and other methods you will learn about later:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/offset_and_limit/tutorial004_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -417,27 +262,14 @@ Of course, you can also combine `.limit()` and `.offset()` with `.where()` and o
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/offset_and_limit/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/offset_and_limit/tutorial004.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Run the Program with Limit, Offset, and Where on the Command Line
|
||||
|
||||
|
||||
@ -8,64 +8,19 @@ We'll create data for this same **many-to-many** relationship with a link table:
|
||||
|
||||
We'll continue from where we left off with the previous code.
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Create Heroes
|
||||
|
||||
As we have done before, we'll create a function `create_heroes()` and we'll create some teams and heroes in it:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="11"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py[ln:36-54]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="11"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py[ln:42-60]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="11"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -74,35 +29,14 @@ As we have done before, we'll create a function `create_heroes()` and we'll crea
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This is very similar to what we have done before.
|
||||
|
||||
@ -116,32 +50,6 @@ See how **Deadpond** now belongs to the two teams?
|
||||
|
||||
Now let's do as we have done before, `commit` the **session**, `refresh` the data, and print it:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="22-25 27-29 31-36"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py[ln:36-69]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="22-25 27-29 31-36"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py[ln:42-75]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="22-25 27-29 31-36"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -150,67 +58,20 @@ Now let's do as we have done before, `commit` the **session**, `refresh` the dat
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Add to Main
|
||||
|
||||
As before, add the `create_heroes()` function to the `main()` function to make sure it is called when running this program from the command line:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py[ln:72-74]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py[ln:78-80]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python
|
||||
```Python hl_lines="22-25 27-29 31-36"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001.py[ln:78-80]!}
|
||||
@ -218,35 +79,14 @@ As before, add the `create_heroes()` function to the `main()` function to make s
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Run the Program
|
||||
|
||||
@ -270,7 +110,7 @@ INFO Engine INSERT INTO hero (name, secret_name, age) VALUES (?, ?, ?)
|
||||
INFO Engine [cached since 0.002541s ago] ('Spider-Boy', 'Pedro Parqueador', None)
|
||||
// Insert the team data second
|
||||
INFO Engine INSERT INTO team (name, headquarters) VALUES (?, ?)
|
||||
INFO Engine [generated in 0.00037s] ('Z-Force', 'Sister Margaret's Bar')
|
||||
INFO Engine [generated in 0.00037s] ('Z-Force', 'Sister Margaret’s Bar')
|
||||
INFO Engine INSERT INTO team (name, headquarters) VALUES (?, ?)
|
||||
INFO Engine [cached since 0.001239s ago] ('Preventers', 'Sharp Tower')
|
||||
// Insert the link data last, to be able to re-use the created IDs
|
||||
@ -305,7 +145,7 @@ WHERE ? = heroteamlink.hero_id AND team.id = heroteamlink.team_id
|
||||
INFO Engine [generated in 0.00025s] (1,)
|
||||
|
||||
// Print Deadpond's teams, 2 teams! 🎉
|
||||
Deadpond teams: [Team(id=1, name='Z-Force', headquarters='Sister Margaret's Bar'), Team(id=2, name='Preventers', headquarters='Sharp Tower')]
|
||||
Deadpond teams: [Team(id=1, name='Z-Force', headquarters='Sister Margaret’s Bar'), Team(id=2, name='Preventers', headquarters='Sharp Tower')]
|
||||
|
||||
// Print Rusty-Man
|
||||
Rusty-Man: name='Rusty-Man' age=48 id=2 secret_name='Tommy Sharp'
|
||||
|
||||
@ -12,63 +12,20 @@ As we want to support a **many-to-many** relationship, now we need a **link tabl
|
||||
|
||||
We can create it just as any other **SQLModel**:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="4-6"
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py[ln:1-6]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="6-12"
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py[ln:1-12]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="6-12"
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001.py[ln:1-12]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This is a **SQLModel** class model table like any other.
|
||||
|
||||
@ -82,32 +39,6 @@ And **both fields are primary keys**. We hadn't used this before. 🤓
|
||||
|
||||
Let's see the `Team` model, it's almost identical as before, but with a little change:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py[ln:9-14]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py[ln:15-20]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -116,35 +47,14 @@ Let's see the `Team` model, it's almost identical as before, but with a little c
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
The **relationship attribute `heroes`** is still a list of heroes, annotated as `List["Hero"]`. Again, we use `"Hero"` in quotes because we haven't declared that class yet by this point in the code (but as you know, editors and **SQLModel** understand that).
|
||||
|
||||
@ -158,32 +68,6 @@ And here's the important part to allow the **many-to-many** relationship, we use
|
||||
|
||||
Let's see the other side, here's the `Hero` model:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py[ln:17-23]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py[ln:23-29]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -192,35 +76,14 @@ Let's see the other side, here's the `Hero` model:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
We **removed** the previous `team_id` field (column) because now the relationship is done via the link table. 🔥
|
||||
|
||||
@ -238,32 +101,6 @@ And now we have a **`link_model=HeroTeamLink`**. ✨
|
||||
|
||||
The same as before, we will have the rest of the code to create the **engine**, and a function to create all the tables `create_db_and_tables()`.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py[ln:26-33]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py[ln:32-39]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -272,67 +109,18 @@ The same as before, we will have the rest of the code to create the **engine**,
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
|
||||
And as in previous examples, we will add that function to a function `main()`, and we will call that `main()` function in the main block:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="4"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py[ln:72-73]!}
|
||||
# We will do more stuff here later 👈
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py[ln:77-78]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="4"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py[ln:78-79]!}
|
||||
# We will do more stuff here later 👈
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py[ln:83-84]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="4"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -342,35 +130,14 @@ And as in previous examples, we will add that function to a function `main()`, a
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001.py[ln:83-84]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
|
||||
## Run the Code
|
||||
|
||||
@ -26,15 +26,12 @@ The `team` table looks like this:
|
||||
<td>1</td><td>Preventers</td><td>Sharp Tower</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>2</td><td>Z-Force</td><td>Sister Margaret's Bar</td>
|
||||
<td>2</td><td>Z-Force</td><td>Sister Margaret’s Bar</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
/// tip
|
||||
|
||||
Notice that it doesn't have any foreign key to other tables.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Notice that it doesn't have any foreign key to other tables.
|
||||
|
||||
And the `hero` table looks like this:
|
||||
|
||||
@ -109,22 +106,19 @@ Specifically, the new link table `heroteamlink` would be:
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
/// info
|
||||
!!! info
|
||||
Other names used for this **link table** are:
|
||||
|
||||
Other names used for this **link table** are:
|
||||
* association table
|
||||
* secondary table
|
||||
* junction table
|
||||
* intermediate table
|
||||
* join table
|
||||
* through table
|
||||
* relationship table
|
||||
* connection table
|
||||
|
||||
* association table
|
||||
* secondary table
|
||||
* junction table
|
||||
* intermediate table
|
||||
* join table
|
||||
* through table
|
||||
* relationship table
|
||||
* connection table
|
||||
|
||||
I'm using the term "link table" because it's short, doesn't collide with other terms already used (e.g. "relationship"), it's easy to remember how to write it, etc.
|
||||
|
||||
///
|
||||
I'm using the term "link table" because it's short, doesn't collide with other terms already used (e.g. "relationship"), it's easy to remember how to write it, etc.
|
||||
|
||||
## Link Primary Key
|
||||
|
||||
|
||||
@ -18,11 +18,8 @@ A row in the table `heroteamlink` points to **one** particular hero, but a singl
|
||||
|
||||
And also, the same row in the table `heroteamlink` points to **one** team, but a single team can be connected to **many** hero-team links, so it's also **one-to-many**.
|
||||
|
||||
/// tip
|
||||
|
||||
The previous many-to-many relationship was also just two one-to-many relationships combined, but now it's going to be much more explicit.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
The previous many-to-many relationship was also just two one-to-many relationships combined, but now it's going to be much more explicit.
|
||||
|
||||
## Update Link Model
|
||||
|
||||
@ -32,32 +29,6 @@ We will add a new field `is_training`.
|
||||
|
||||
And we will also add two **relationship attributes**, for the linked `team` and `hero`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="6 8-9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py310.py[ln:4-10]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="10 12-13"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py39.py[ln:6-16]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="10 12-13"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -66,48 +37,24 @@ And we will also add two **relationship attributes**, for the linked `team` and
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
The new **relationship attributes** have their own `back_populates` pointing to new relationship attributes we will create in the `Hero` and `Team` models:
|
||||
|
||||
* `team`: has `back_populates="hero_links"`, because in the `Team` model, the attribute will contain the links to the **team's heroes**.
|
||||
* `hero`: has `back_populates="team_links"`, because in the `Hero` model, the attribute will contain the links to the **hero's teams**.
|
||||
|
||||
/// info
|
||||
!!! info
|
||||
In SQLAlchemy this is called an Association Object or Association Model.
|
||||
|
||||
In SQLAlchemy this is called an Association Object or Association Model.
|
||||
|
||||
I'm calling it **Link Model** just because that's easier to write avoiding typos. But you are also free to call it however you want. 😉
|
||||
|
||||
///
|
||||
I'm calling it **Link Model** just because that's easier to write avoiding typos. But you are also free to call it however you want. 😉
|
||||
|
||||
## Update Team Model
|
||||
|
||||
@ -115,32 +62,6 @@ Now let's update the `Team` model.
|
||||
|
||||
We no longer have the `heroes` relationship attribute, and instead we have the new `hero_links` attribute:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py310.py[ln:13-18]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py39.py[ln:19-24]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -149,35 +70,14 @@ We no longer have the `heroes` relationship attribute, and instead we have the n
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Update Hero Model
|
||||
|
||||
@ -185,32 +85,6 @@ The same with the `Hero` model.
|
||||
|
||||
We change the `teams` relationship attribute for `team_links`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py310.py[ln:21-27]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py39.py[ln:27-33]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -219,35 +93,14 @@ We change the `teams` relationship attribute for `team_links`:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Create Relationships
|
||||
|
||||
@ -255,32 +108,6 @@ Now the process to create relationships is very similar.
|
||||
|
||||
But now we create the **explicit link models** manually, pointing to their hero and team instances, and specifying the additional link data (`is_training`):
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="21-30 32-35"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py310.py[ln:40-79]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="21-30 32-35"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py39.py[ln:46-85]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="21-30 32-35"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -289,35 +116,14 @@ But now we create the **explicit link models** manually, pointing to their hero
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
We are just adding the link model instances to the session, because the link model instances are connected to the heroes and teams, they will be also automatically included in the session when we commit.
|
||||
|
||||
@ -345,7 +151,7 @@ INFO Engine [cached since 0.001858s ago] ('Rusty-Man', 'Tommy Sharp', 48)
|
||||
|
||||
// Insert the teams
|
||||
INFO Engine INSERT INTO team (name, headquarters) VALUES (?, ?)
|
||||
INFO Engine [generated in 0.00019s] ('Z-Force', 'Sister Margaret's Bar')
|
||||
INFO Engine [generated in 0.00019s] ('Z-Force', 'Sister Margaret’s Bar')
|
||||
INFO Engine INSERT INTO team (name, headquarters) VALUES (?, ?)
|
||||
INFO Engine [cached since 0.0007985s ago] ('Preventers', 'Sharp Tower')
|
||||
|
||||
@ -415,32 +221,6 @@ Now, to add a new relationship, we have to create a new `HeroTeamLink` instance
|
||||
|
||||
Here we do that in the `update_heroes()` function:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="10-15"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py310.py[ln:82-97]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="10-15"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py39.py[ln:88-103]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="10-15"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -449,35 +229,14 @@ Here we do that in the `update_heroes()` function:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Run the Program with the New Relationship
|
||||
|
||||
@ -558,40 +317,6 @@ So now we want to update the status of `is_training` to `False`.
|
||||
|
||||
We can do that by iterating on the links:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="8-10"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py310.py[ln:82-83]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py310.py[ln:99-107]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="8-10"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py39.py[ln:88-89]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py39.py[ln:105-113]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="8-10"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -604,35 +329,14 @@ We can do that by iterating on the links:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial003.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Run the Program with the Updated Relationships
|
||||
|
||||
@ -685,7 +389,7 @@ WHERE team.id = ?
|
||||
INFO Engine [cached since 0.2097s ago] (1,)
|
||||
|
||||
// Print Spider-Boy team, including link data, if is training
|
||||
Spider-Boy team: headquarters='Sister Margaret's Bar' id=1 name='Z-Force' is training: True
|
||||
Spider-Boy team: headquarters='Sister Margaret’s Bar' id=1 name='Z-Force' is training: True
|
||||
INFO Engine ROLLBACK
|
||||
```
|
||||
|
||||
|
||||
@ -4,33 +4,14 @@ Now we'll see how to update and remove these **many-to-many** relationships.
|
||||
|
||||
We'll continue from where we left off with the previous code.
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Get Data to Update
|
||||
|
||||
@ -42,36 +23,6 @@ As you already know how these goes, I'll use the **short version** and get the d
|
||||
|
||||
And because we are now using `select()`, we also have to import it.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="1 5-10"
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002_py310.py[ln:1]!}
|
||||
|
||||
# Some code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002_py310.py[ln:72-77]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3 7-12"
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002_py39.py[ln:1-3]!}
|
||||
|
||||
# Some code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002_py39.py[ln:78-83]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3 7-12"
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002.py[ln:1-3]!}
|
||||
|
||||
@ -82,95 +33,31 @@ And because we are now using `select()`, we also have to import it.
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
And of course, we have to add `update_heroes()` to our `main()` function:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="6"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002_py310.py[ln:94-101]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="6"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002_py39.py[ln:100-107]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="6"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002.py[ln:100-107]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Add Many-to-Many Relationships
|
||||
|
||||
@ -178,32 +65,6 @@ Now let's imagine that **Spider-Boy** thinks that the **Z-Force** team is super
|
||||
|
||||
We can use the same **relationship attributes** to include `hero_spider_boy` in the `team_z_force.heroes`.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="10-12 14-15"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002_py310.py[ln:72-84]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="10-12 14-15"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002_py39.py[ln:78-90]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="10-12 14-15"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -212,43 +73,19 @@ We can use the same **relationship attributes** to include `hero_spider_boy` in
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
</details>
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Because we are accessing an attribute in the models right after we commit, with `hero_spider_boy.teams` and `team_z_force.heroes`, the data is refreshed automatically.
|
||||
|
||||
/// tip
|
||||
|
||||
Because we are accessing an attribute in the models right after we commit, with `hero_spider_boy.teams` and `team_z_force.heroes`, the data is refreshed automatically.
|
||||
|
||||
So we don't have to call `session.refresh()`.
|
||||
|
||||
///
|
||||
So we don't have to call `session.refresh()`.
|
||||
|
||||
We then commit the change, refresh, and print the updated **Spider-Boy**'s heroes to confirm.
|
||||
|
||||
@ -290,7 +127,7 @@ INFO Engine [cached since 0.1648s ago] (3,)
|
||||
// Print Spider-Boy teams, including Z-Force 🎉
|
||||
Updated Spider-Boy's Teams: [
|
||||
Team(id=2, name='Preventers', headquarters='Sharp Tower'),
|
||||
Team(id=1, name='Z-Force', headquarters='Sister Margaret's Bar')
|
||||
Team(id=1, name='Z-Force', headquarters='Sister Margaret’s Bar')
|
||||
]
|
||||
|
||||
// Automatically refresh the data while accessing the attribute .heores
|
||||
@ -304,7 +141,7 @@ Z-Force heroes: [
|
||||
Hero(name='Deadpond', age=None, id=1, secret_name='Dive Wilson'),
|
||||
Hero(name='Spider-Boy', age=None, id=3, secret_name='Pedro Parqueador', teams=[
|
||||
Team(id=2, name='Preventers', headquarters='Sharp Tower'),
|
||||
Team(id=1, name='Z-Force', headquarters='Sister Margaret's Bar', heroes=[...])
|
||||
Team(id=1, name='Z-Force', headquarters='Sister Margaret’s Bar', heroes=[...])
|
||||
])
|
||||
]
|
||||
```
|
||||
@ -325,32 +162,6 @@ Because `hero_spider_boy.teams` is just a list (a special list managed by SQLAlc
|
||||
|
||||
In this case, we use the method `.remove()`, that takes an item and removes it from the list.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="17-19 21-22"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002_py310.py[ln:72-91]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="17-19 21-22"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002_py39.py[ln:78-97]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="17-19 21-22"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -359,35 +170,14 @@ In this case, we use the method `.remove()`, that takes an item and removes it f
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/many_to_many/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
And this time, just to show again that by using `back_populates` **SQLModel** (actually SQLAlchemy) takes care of connecting the models by their relationships, even though we performed the operation from the `hero_spider_boy` object (modifying `hero_spider_boy.teams`), we are adding `team_z_force` to the **session**. And we commit that, without even add `hero_spider_boy`.
|
||||
|
||||
|
||||
@ -14,25 +14,14 @@ Let's see the utilities to read a single row.
|
||||
|
||||
We'll continue with the same examples we have been using in the previous chapters to create and select data and we'll keep updating them.
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/indexes/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/indexes/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
If you already executed the previous examples and have a database with data, **remove the database file** before running each example, that way you won't have duplicate data and you will be able to get the same results.
|
||||
|
||||
@ -40,20 +29,6 @@ If you already executed the previous examples and have a database with data, **r
|
||||
|
||||
We have been iterating over the rows in a `result` object like:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="7-8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/indexes/tutorial002_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="7-8"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -62,46 +37,19 @@ We have been iterating over the rows in a `result` object like:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/indexes/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/indexes/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
But let's say that we are not interested in all the rows, just the **first** one.
|
||||
|
||||
We can call the `.first()` method on the `results` object to get the first row:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="7"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/one/tutorial001_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="7"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -110,37 +58,21 @@ We can call the `.first()` method on the `results` object to get the first row:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/one/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/one/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This will return the first object in the `results` (if there was any).
|
||||
|
||||
That way, we don't have to deal with an iterable or a list.
|
||||
|
||||
/// tip
|
||||
|
||||
Notice that `.first()` is a method of the `results` object, not of the `select()` statement.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Notice that `.first()` is a method of the `results` object, not of the `select()` statement.
|
||||
|
||||
Although this query would find two rows, by using `.first()` we get only the first row.
|
||||
|
||||
@ -171,20 +103,6 @@ It would be possible that the SQL query doesn't find any row.
|
||||
|
||||
In that case, `.first()` will return `None`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5 7"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/one/tutorial002_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5 7"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -193,27 +111,14 @@ In that case, `.first()` will return `None`:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/one/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/one/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
In this case, as there's no hero with an age less than 25, `.first()` will return `None`.
|
||||
|
||||
@ -246,20 +151,6 @@ And if there was more than one, it would mean that there's an error in the syste
|
||||
|
||||
In that case, instead of `.first()` we can use `.one()`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="7"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/one/tutorial003_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="7"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -268,27 +159,14 @@ In that case, instead of `.first()` we can use `.one()`:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/one/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/one/tutorial003.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Here we know that there's only one `"Deadpond"`, and there shouldn't be any more than one.
|
||||
|
||||
@ -344,20 +222,6 @@ sqlalchemy.exc.MultipleResultsFound: Multiple rows were found when exactly one w
|
||||
|
||||
Of course, even if we don't duplicate the data, we could get the same error if we send a query that finds more than one row and expect exactly one with `.one()`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5 7"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/one/tutorial004_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5 7"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -366,27 +230,14 @@ Of course, even if we don't duplicate the data, we could get the same error if w
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/one/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/one/tutorial004.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
That would find 2 rows, and would end up with the same error.
|
||||
|
||||
@ -394,20 +245,6 @@ That would find 2 rows, and would end up with the same error.
|
||||
|
||||
And also, if we get no rows at all with `.one()`, it will also raise an error:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5 7"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/one/tutorial005_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5 7"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -416,27 +253,14 @@ And also, if we get no rows at all with `.one()`, it will also raise an error:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/one/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/one/tutorial005.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
In this case, as there are no heroes with an age less than 25, `.one()` will raise an error.
|
||||
|
||||
@ -469,20 +293,6 @@ sqlalchemy.exc.NoResultFound: No row was found when one was required
|
||||
|
||||
Of course, with `.first()` and `.one()` you would also probably write all that in a more compact form most of the time, all in a single line (or at least a single Python statement):
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/one/tutorial006_py310.py[ln:42-45]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -491,27 +301,14 @@ Of course, with `.first()` and `.one()` you would also probably write all that i
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/one/tutorial006_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/one/tutorial006.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
That would result in the same as some examples above.
|
||||
|
||||
@ -521,20 +318,6 @@ In many cases you might want to select a single row by its Id column with the **
|
||||
|
||||
You could do it the same way we have been doing with a `.where()` and then getting the first item with `.first()`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5 7"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/one/tutorial007_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5 7"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -543,27 +326,14 @@ You could do it the same way we have been doing with a `.where()` and then getti
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/one/tutorial007_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/one/tutorial007.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
That would work correctly, as expected. But there's a shorter version. 👇
|
||||
|
||||
@ -571,20 +341,6 @@ That would work correctly, as expected. But there's a shorter version. 👇
|
||||
|
||||
As selecting a single row by its Id column with the **primary key** is a common operation, there's a shortcut for it:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/one/tutorial008_py310.py[ln:42-45]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -593,27 +349,14 @@ As selecting a single row by its Id column with the **primary key** is a common
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/one/tutorial008_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/one/tutorial008.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
`session.get(Hero, 1)` is an equivalent to creating a `select()`, then filtering by Id using `.where()`, and then getting the first item with `.first()`.
|
||||
|
||||
@ -642,20 +385,6 @@ Hero: secret_name='Dive Wilson' age=None id=1 name='Deadpond'
|
||||
|
||||
`.get()` behaves similar to `.first()`, if there's no data it will simply return `None` (instead of raising an error):
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/one/tutorial009_py310.py[ln:42-45]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -664,27 +393,14 @@ Hero: secret_name='Dive Wilson' age=None id=1 name='Deadpond'
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/one/tutorial009_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/one/tutorial009.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Running that will output:
|
||||
|
||||
@ -710,4 +426,4 @@ Hero: None
|
||||
|
||||
## Recap
|
||||
|
||||
As querying the SQL database for a single row is a common operation, you now have several tools to do it in a short and simple way. 🎉
|
||||
As querying the SQL database for a single row is a common operation, you know have several tools to do it in a short and simple way. 🎉
|
||||
|
||||
@ -20,63 +20,20 @@ Let's understand that better with an example.
|
||||
|
||||
Let's see how that works by writing an **incomplete** version first, without `back_populates`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="9 19"
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py310.py[ln:1-19]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="11 21"
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py39.py[ln:1-21]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="11 21"
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001.py[ln:1-21]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Read Data Objects
|
||||
|
||||
@ -84,32 +41,6 @@ Now, we will get the **Spider-Boy** hero and, *independently*, the **Preventers*
|
||||
|
||||
As you already know how this works, I won't separate that in a select `statement`, `results`, etc. Let's use the shorter form in a single call:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5-7 9-11"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py310.py[ln:103-111]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="5-7 9-11"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py39.py[ln:105-113]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5-7 9-11"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -118,72 +49,22 @@ As you already know how this works, I won't separate that in a select `statement
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
</details>
|
||||
|
||||
///
|
||||
|
||||
/// tip
|
||||
|
||||
When writing your own code, this is probably the style you will use most often, as it's shorter, more convenient, and you still get all the power of autocompletion and inline errors.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
When writing your own code, this is probably the style you will use most often, as it's shorter, more convenient, and you still get all the power of autocompletion and inline errors.
|
||||
|
||||
## Print the Data
|
||||
|
||||
Now, let's print the current **Spider-Boy**, the current **Preventers** team, and particularly, the current **Preventers** list of heroes:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="13-15"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py310.py[ln:103-115]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="13-15"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py39.py[ln:105-117]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="13-15"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -192,35 +73,14 @@ Now, let's print the current **Spider-Boy**, the current **Preventers** team, an
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Up to this point, it's all good. 😊
|
||||
|
||||
@ -242,40 +102,6 @@ Notice that we have **Spider-Boy** there.
|
||||
|
||||
Now let's update **Spider-Boy**, removing him from the team by setting `hero_spider_boy.team = None` and then let's print this object again:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="8 12"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py310.py[ln:103-104]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py310.py[ln:117-121]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="8 12"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py39.py[ln:105-106]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py39.py[ln:119-123]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="8 12"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -288,45 +114,21 @@ Now let's update **Spider-Boy**, removing him from the team by setting `hero_spi
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
The first important thing is, we *haven't committed* the hero yet, so accessing the list of heroes would not trigger an automatic refresh.
|
||||
|
||||
But in our code, in this exact point in time, we already said that **Spider-Boy** is no longer part of the **Preventers**. 🔥
|
||||
|
||||
/// tip
|
||||
|
||||
We could revert that later by not committing the **session**, but that's not what we are interested in here.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
We could revert that later by not committing the **session**, but that's not what we are interested in here.
|
||||
|
||||
Here, at this point in the code, in memory, the code expects **Preventers** to *not include* **Spider-Boy**.
|
||||
|
||||
@ -356,40 +158,6 @@ Oh, no! 😱 **Spider-Boy** is still listed there!
|
||||
|
||||
Now, if we commit it and print again:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="8-9 15"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py310.py[ln:103-104]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py310.py[ln:123-130]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="8-9 15"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py39.py[ln:105-106]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py39.py[ln:125-132]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="8-9 15"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -402,35 +170,14 @@ Now, if we commit it and print again:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
When we access `preventers_team.heroes` after the `commit`, that triggers a refresh, so we get the latest list, without **Spider-Boy**, so that's fine again:
|
||||
|
||||
@ -462,100 +209,23 @@ That's what `back_populates` is for. ✨
|
||||
|
||||
Let's add it back:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="9 19"
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py310.py[ln:1-19]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="11 21"
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py39.py[ln:1-21]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="11 21"
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002.py[ln:1-21]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
And we can keep the rest of the code the same:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="8 12"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py310.py[ln:103-104]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py310.py[ln:117-121]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="8 12"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py39.py[ln:105-106]!}
|
||||
|
||||
# Code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py39.py[ln:119-123]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="8 12"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -568,43 +238,19 @@ And we can keep the rest of the code the same:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
</details>
|
||||
|
||||
///
|
||||
!!! tip
|
||||
This is the same section where we updated `hero_spider_boy.team` to `None` but we *haven't committed* that change yet.
|
||||
|
||||
/// tip
|
||||
|
||||
This is the same section where we updated `hero_spider_boy.team` to `None` but we *haven't committed* that change yet.
|
||||
|
||||
The same section that caused a problem before.
|
||||
|
||||
///
|
||||
The same section that caused a problem before.
|
||||
|
||||
## Review the Result
|
||||
|
||||
@ -629,63 +275,20 @@ Now that you know why `back_populates` is there, let's review the exact value ag
|
||||
|
||||
It's quite simple code, it's just a string, but it might be confusing to think exactly *what* string should go there:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="9 19"
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py310.py[ln:1-19]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="11 21"
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py39.py[ln:1-21]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="11 21"
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002.py[ln:1-21]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
The string in `back_populates` is the name of the attribute *in the other* model, that will reference *the current* model.
|
||||
|
||||
@ -693,32 +296,6 @@ The string in `back_populates` is the name of the attribute *in the other* model
|
||||
|
||||
So, in the class `Team`, we have an attribute `heroes` and we declare it with `Relationship(back_populates="team")`.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py310.py[ln:4-9]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py39.py[ln:6-11]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -727,35 +304,14 @@ So, in the class `Team`, we have an attribute `heroes` and we declare it with `R
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
The string in `back_populates="team"` refers to the attribute `team` in the class `Hero` (the other class).
|
||||
|
||||
@ -763,32 +319,6 @@ And, in the class `Hero`, we declare an attribute `team`, and we declare it with
|
||||
|
||||
So, the string `"heroes"` refers to the attribute `heroes` in the class `Team`.
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="10"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py310.py[ln:12-19]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="10"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py39.py[ln:14-21]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="10"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -797,41 +327,17 @@ So, the string `"heroes"` refers to the attribute `heroes` in the class `Team`.
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
</details>
|
||||
|
||||
///
|
||||
|
||||
/// tip
|
||||
|
||||
Each **relationship attribute** points to the other one, in the other model, using `back_populates`.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Each **relationship attribute** points to the other one, in the other model, using `back_populates`.
|
||||
|
||||
Although it's simple code, it can be confusing to think about 😵, because the same line has concepts related to both models in multiple places:
|
||||
|
||||
@ -850,32 +356,6 @@ So, `back_populates` would most probably be something like `"hero"` or `"heroes"
|
||||
|
||||
<img src="/img/tutorial/relationships/attributes/back-populates2.svg">
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3 10 13 15"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial003_py310.py[ln:27-39]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3 10 13 15"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial003_py39.py[ln:29-41]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3 10 13 15"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -884,32 +364,11 @@ So, `back_populates` would most probably be something like `"hero"` or `"heroes"
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial003_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/back_populates/tutorial003.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
@ -6,20 +6,6 @@ Let's see now how to create data with relationships using these new **relationsh
|
||||
|
||||
Let's check the old code we used to create some heroes and teams:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="9 12 18 24"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001_py310.py[ln:29-58]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="9 12 18 24"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -28,27 +14,14 @@ Let's check the old code we used to create some heroes and teams:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
There are several things to **notice** here.
|
||||
|
||||
@ -68,32 +41,6 @@ This is the first area where these **relationship attributes** can help. 🤓
|
||||
|
||||
Now let's do all that, but this time using the new, shiny `Relationship` attributes:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="9 12 18"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001_py310.py[ln:32-55]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="9 12 18"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001_py39.py[ln:34-57]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="9 12 18"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -102,39 +49,18 @@ Now let's do all that, but this time using the new, shiny `Relationship` attribu
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Now we can create the `Team` instances and pass them directly to the new `team` argument when creating the `Hero` instances, as `team=team_preventers` instead of `team_id=team_preventers.id`.
|
||||
|
||||
And thanks to SQLAlchemy and how it works underneath, these teams don't even need to have an ID yet, but because we are assigning the whole object to each hero, those teams **will be automatically created** in the database, the automatic ID will be generated, and will be set in the `team_id` column for each of the corresponding hero rows.
|
||||
And thanks to SQLAlchemy and how it works underneath, these teams don't even have to have an ID yet, but because we are assigning the whole object to each hero, those teams **will be automatically created** in the database, the automatic ID will be generated, and will be set in the `team_id` column for each of the corresponding hero rows.
|
||||
|
||||
In fact, now we don't even have to put the teams explicitly in the session with `session.add(team)`, because these `Team` instances are **already associated** with heroes that **we do** `add` to the session.
|
||||
|
||||
@ -146,40 +72,6 @@ And then, as you can see, we only have to do one `commit()`.
|
||||
|
||||
The same way we could assign an integer with a `team.id` to a `hero.team_id`, we can also assign the `Team` instance to the `hero.team`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001_py310.py[ln:32-33]!}
|
||||
|
||||
# Previous code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001_py310.py[ln:57-61]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001_py39.py[ln:34-35]!}
|
||||
|
||||
# Previous code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001_py39.py[ln:59-63]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="8"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -192,35 +84,14 @@ The same way we could assign an integer with a `team.id` to a `hero.team_id`, we
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Create a Team with Heroes
|
||||
|
||||
@ -228,40 +99,6 @@ Before, we created some `Team` instances and passed them in the `team=` argument
|
||||
|
||||
We could also create the `Hero` instances first, and then pass them in the `heroes=` argument that takes a list, when creating a `Team` instance:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="13 15-16"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001_py310.py[ln:32-33]!}
|
||||
|
||||
# Previous code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001_py310.py[ln:63-73]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="13 15-16"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001_py39.py[ln:34-35]!}
|
||||
|
||||
# Previous code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001_py39.py[ln:65-75]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="13 15-16"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -274,35 +111,14 @@ We could also create the `Hero` instances first, and then pass them in the `hero
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Here we create two heroes first, **Black Lion** and **Princess Sure-E**, and then we pass them in the `heroes` argument.
|
||||
|
||||
@ -318,40 +134,6 @@ As the attribute `team.heroes` behaves like a list, we can simply append to it.
|
||||
|
||||
Let's create some more heroes and add them to the `team_preventers.heroes` list attribute:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="14-18"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001_py310.py[ln:32-33]!}
|
||||
|
||||
# Previous code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001_py310.py[ln:75-91]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="14-18"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001_py39.py[ln:34-35]!}
|
||||
|
||||
# Previous code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001_py39.py[ln:77-93]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="14-18"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -364,35 +146,14 @@ Let's create some more heroes and add them to the `team_preventers.heroes` list
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
The attribute `team_preventers.heroes` behaves like a list. But it's a special type of list, because when we modify it adding heroes to it, **SQLModel** (actually SQLAlchemy) **keeps track of the necessary changes** to be done in the database.
|
||||
|
||||
|
||||
@ -14,7 +14,7 @@ We currently have a `team` table:
|
||||
<td>1</td><td>Preventers</td><td>Sharp Tower</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>2</td><td>Z-Force</td><td>Sister Margaret's Bar</td>
|
||||
<td>2</td><td>Z-Force</td><td>Sister Margaret’s Bar</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
@ -41,45 +41,20 @@ Now that you know how these tables work underneath and how the model classes rep
|
||||
|
||||
Up to now, we have only used the `team_id` column to connect the tables when querying with `select()`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="16"
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001_py310.py[ln:1-16]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="18"
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001.py[ln:1-18]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/connect/insert/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This is a **plain field** like all the others, all representing a **column in the table**.
|
||||
|
||||
@ -87,123 +62,37 @@ But now let's add a couple of new special attributes to these model classes, let
|
||||
|
||||
First, import `Relationship` from `sqlmodel`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001_py310.py[ln:1]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001_py39.py[ln:1-3]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001.py[ln:1-3]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Next, use that `Relationship` to declare a new attribute in the model classes:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="9 19"
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001_py310.py[ln:1-19]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="11 21"
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001_py39.py[ln:1-21]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="11 21"
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001.py[ln:1-21]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## What Are These Relationship Attributes
|
||||
|
||||
@ -234,13 +123,10 @@ And in the `Team` class, the `heroes` attribute is annotated as a list of `Hero`
|
||||
|
||||
**SQLModel** (actually SQLAlchemy) is smart enough to know that the relationship is established by the `team_id`, as that's the foreign key that points from the `hero` table to the `team` table, so we don't have to specify that explicitly here.
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
There's a couple of things we'll check again in some of the next chapters, about the `List["Hero"]` and the `back_populates`.
|
||||
|
||||
There's a couple of things we'll check again in some of the next chapters, about the `List["Hero"]` and the `back_populates`.
|
||||
|
||||
But for now, let's first see how to use these relationship attributes.
|
||||
|
||||
///
|
||||
But for now, let's first see how to use these relationship attributes.
|
||||
|
||||
## Next Steps
|
||||
|
||||
|
||||
@ -4,14 +4,11 @@ In the previous chapters we discussed how to manage databases with tables that h
|
||||
|
||||
And then we read the data together with `select()` and using `.where()` or `.join()` to connect it.
|
||||
|
||||
Now we will see how to use **Relationship Attributes**, an extra feature of **SQLModel** (and SQLAlchemy), to work with the data in the database in a much more familiar way, and closer to normal Python code.
|
||||
Now we will see how to use **Relationship Attributes**, an extra feature of **SQLModel** (and SQLAlchemy) to work with the data in the database in way much more familiar way, and closer to normal Python code.
|
||||
|
||||
/// info
|
||||
!!! info
|
||||
When I say "**relationship**" I mean the standard dictionary term, of data related to other data.
|
||||
|
||||
When I say "**relationship**" I mean the standard dictionary term, of data related to other data.
|
||||
|
||||
I'm not using the term "**relation**" that is the technical, academical, SQL term for a single table.
|
||||
|
||||
///
|
||||
I'm not using the term "**relation**" that is the technical, academical, SQL term for a single table.
|
||||
|
||||
And using those **relationship attributes** is where a tool like **SQLModel** really shines. ✨
|
||||
|
||||
@ -6,40 +6,6 @@ Now that we know how to connect data using **relationship Attributes**, let's se
|
||||
|
||||
First, add a function `select_heroes()` where we get a hero to start working with, and add that function to the `main()` function:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3-7 14"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001_py310.py[ln:94-98]!}
|
||||
|
||||
# Previous code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001_py310.py[ln:108-111]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="3-7 14"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001_py39.py[ln:96-100]!}
|
||||
|
||||
# Previous code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001_py39.py[ln:110-113]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3-7 14"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -52,35 +18,14 @@ First, add a function `select_heroes()` where we get a hero to start working wit
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Select the Related Team - Old Way
|
||||
|
||||
@ -88,32 +33,6 @@ Now that we have a hero, we can get the team this hero belongs to.
|
||||
|
||||
With what we have learned **up to now**, we could use a `select()` statement, then execute it with `session.exec()`, and then get the `.first()` result, for example:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="9-12"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001_py310.py[ln:94-103]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="9-12"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001_py39.py[ln:96-105]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="9-12"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -122,35 +41,14 @@ With what we have learned **up to now**, we could use a `select()` statement, th
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Get Relationship Team - New Way
|
||||
|
||||
@ -158,40 +56,6 @@ But now that we have the **relationship attributes**, we can just access them, a
|
||||
|
||||
So, the highlighted block above, has the same results as the block below:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="11"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001_py310.py[ln:94-98]!}
|
||||
|
||||
# Code from the previous example omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001_py310.py[ln:105]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="11"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001_py39.py[ln:96-100]!}
|
||||
|
||||
# Code from the previous example omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001_py39.py[ln:107]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="11"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -204,74 +68,24 @@ So, the highlighted block above, has the same results as the block below:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
</details>
|
||||
|
||||
///
|
||||
!!! tip
|
||||
The automatic data fetching will work as long as the starting object (in this case the `Hero`) is associated with an **open** session.
|
||||
|
||||
/// tip
|
||||
|
||||
The automatic data fetching will work as long as the starting object (in this case the `Hero`) is associated with an **open** session.
|
||||
|
||||
For example, here, **inside** a `with` block with a `Session` object.
|
||||
|
||||
///
|
||||
For example, here, **inside** a `with` block with a `Session` object.
|
||||
|
||||
## Get a List of Relationship Objects
|
||||
|
||||
And the same way, when we are working on the **many** side of the **one-to-many** relationship, we can get a list of of the related objects just by accessing the relationship attribute:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial002_py310.py[ln:94-100]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial002_py39.py[ln:96-102]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -280,35 +94,14 @@ And the same way, when we are working on the **many** side of the **one-to-many*
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
That would print a list with all the heroes in the Preventers team:
|
||||
|
||||
|
||||
@ -8,32 +8,6 @@ And then for some reason needs to leave the **Preventers** for some years. 😭
|
||||
|
||||
We can remove the relationship by setting it to `None`, the same as with the `team_id`, it also works with the new relationship attribute `.team`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial002_py310.py[ln:103-114]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial002_py39.py[ln:105-116]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="9"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -42,64 +16,17 @@ We can remove the relationship by setting it to `None`, the same as with the `te
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
And of course, we should remember to add this `update_heroes()` function to `main()` so that it runs when we call this program from the command line:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="7"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial002_py310.py[ln:117-121]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="7"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial002_py39.py[ln:119-123]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="7"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -108,35 +35,14 @@ And of course, we should remember to add this `update_heroes()` function to `mai
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial002_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/read_relationships/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Recap
|
||||
|
||||
|
||||
@ -2,63 +2,20 @@
|
||||
|
||||
In the first Relationship attribute, we declare it with `List["Hero"]`, putting the `Hero` in quotes instead of just normally there:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001_py310.py[ln:1-19]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001_py39.py[ln:1-21]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="11"
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001.py[ln:1-21]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.9+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001_py39.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/relationship_attributes/define_relationship_attributes/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
What's that about? Can't we just write it normally as `List[Hero]`?
|
||||
|
||||
@ -72,8 +29,5 @@ And of course, **SQLModel** can also understand it in the string correctly. ✨
|
||||
|
||||
That is actually part of Python, it's the current official solution to handle it.
|
||||
|
||||
/// info
|
||||
|
||||
There's a lot of work going on in Python itself to make that simpler and more intuitive, and find ways to make it possible to not wrap the class in a string.
|
||||
|
||||
///
|
||||
!!! info
|
||||
There's a lot of work going on in Python itself to make that simpler and more intuitive, and find ways to make it possible to not wrap the class in a string.
|
||||
|
||||
@ -23,25 +23,14 @@ Things are getting more exciting! Let's now see how to read data from the databa
|
||||
|
||||
Let's continue from the last code we used to create some data.
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/insert/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
We are creating a **SQLModel** `Hero` class model and creating some records.
|
||||
|
||||
@ -90,15 +79,12 @@ You can try that out in **DB Browser for SQLite**:
|
||||
|
||||
<img class="shadow" src="/img/tutorial/select/image01.png">
|
||||
|
||||
/// warning
|
||||
!!! warning
|
||||
Here we are getting all the rows.
|
||||
|
||||
Here we are getting all the rows.
|
||||
If you have thousands of rows, that could be expensive to compute for the database.
|
||||
|
||||
If you have thousands of rows, that could be expensive to compute for the database.
|
||||
|
||||
You would normally want to filter the rows to receive only the ones you want. But we'll learn about that later in the next chapter.
|
||||
|
||||
///
|
||||
You would normally want to filter the rows to receive only the ones you want. But we'll learn about that later in the next chapter.
|
||||
|
||||
### A SQL Shortcut
|
||||
|
||||
@ -178,20 +164,6 @@ The first step is to create a **Session**, the same way we did when creating the
|
||||
|
||||
We will start with that in a new function `select_heroes()`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="3-4"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/select/tutorial001_py310.py[ln:34-35]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3-4"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -200,27 +172,14 @@ We will start with that in a new function `select_heroes()`:
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Create a `select` Statement
|
||||
|
||||
@ -228,64 +187,23 @@ Next, pretty much the same way we wrote a SQL `SELECT` statement above, now we'l
|
||||
|
||||
First we have to import `select` from `sqlmodel` at the top of the file:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!./docs_src/tutorial/select/tutorial001_py310.py[ln:1]!}
|
||||
|
||||
# More code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!./docs_src/tutorial/select/tutorial001.py[ln:1-3]!}
|
||||
|
||||
# More code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
And then we will use it to create a `SELECT` statement in Python code:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="7"
|
||||
{!./docs_src/tutorial/select/tutorial001_py310.py[ln:1]!}
|
||||
|
||||
# More code here omitted 👈
|
||||
|
||||
{!./docs_src/tutorial/select/tutorial001_py310.py[ln:34-36]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="9"
|
||||
{!./docs_src/tutorial/select/tutorial001.py[ln:1-3]!}
|
||||
|
||||
@ -296,27 +214,14 @@ And then we will use it to create a `SELECT` statement in Python code:
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
It's a very simple line of code that conveys a lot of information:
|
||||
|
||||
@ -335,32 +240,15 @@ We pass the class model `Hero` to the `select()` function. And that tells it tha
|
||||
|
||||
And notice that in the `select()` function we don't explicitly specify the `FROM` part. It is already obvious to **SQLModel** (actually to SQLAlchemy) that we want to select `FROM` the table `hero`, because that's the one associated with the `Hero` class model.
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
The value of the `statement` returned by `select()` is a special object that allows us to do other things.
|
||||
|
||||
The value of the `statement` returned by `select()` is a special object that allows us to do other things.
|
||||
|
||||
I'll tell you about that in the next chapters.
|
||||
|
||||
///
|
||||
I'll tell you about that in the next chapters.
|
||||
|
||||
## Execute the Statement
|
||||
|
||||
Now that we have the `select` statement, we can execute it with the **session**:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="6"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/select/tutorial001_py310.py[ln:34-37]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="6"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -369,27 +257,14 @@ Now that we have the `select` statement, we can execute it with the **session**:
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This will tell the **session** to go ahead and use the **engine** to execute that `SELECT` statement in the database and bring the results back.
|
||||
|
||||
@ -427,20 +302,6 @@ The `results` object is an <abbr title="Something that can be used in a for loop
|
||||
|
||||
Now we can put it in a `for` loop and print each one of the heroes:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="7-8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/select/tutorial001_py310.py[ln:34-39]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="7-8"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -449,27 +310,14 @@ Now we can put it in a `for` loop and print each one of the heroes:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This will print the output:
|
||||
|
||||
@ -483,20 +331,6 @@ id=3 name='Rusty-Man' age=48 secret_name='Tommy Sharp'
|
||||
|
||||
Now include a call to `select_heroes()` in the `main()` function so that it is executed when we run the program from the command line:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="14"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/select/tutorial001_py310.py[ln:34-45]!}
|
||||
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="14"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -505,27 +339,14 @@ Now include a call to `select_heroes()` in the `main()` function so that it is e
|
||||
# More code here later 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Review The Code
|
||||
|
||||
@ -533,31 +354,14 @@ Great, you're now being able to read the data from the database! 🎉
|
||||
|
||||
Let's review the code up to this point:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```{ .python .annotate }
|
||||
{!./docs_src/tutorial/select/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
{!./docs_src/tutorial/select/annotations/en/tutorial002.md!}
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```{ .python .annotate }
|
||||
{!./docs_src/tutorial/select/tutorial002.py!}
|
||||
```
|
||||
|
||||
{!./docs_src/tutorial/select/annotations/en/tutorial002.md!}
|
||||
|
||||
////
|
||||
|
||||
/// tip
|
||||
|
||||
Check out the number bubbles to see what is done by each line of code.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Check out the number bubbles to see what is done by each line of code.
|
||||
|
||||
Here it starts to become more evident why we should have a single **engine** for the whole application, but different **sessions** for each group of operations.
|
||||
|
||||
@ -569,13 +373,10 @@ And the second section reading data from the database could be in another functi
|
||||
|
||||
So, both sections could be in **different places** and would need their own sessions.
|
||||
|
||||
/// info
|
||||
!!! info
|
||||
To be fair, in this example all that code could actually share the same **session**, there's actually no need to have two here.
|
||||
|
||||
To be fair, in this example all that code could actually share the same **session**, there's actually no need to have two here.
|
||||
|
||||
But it allows me to show you how they could be separated and to reinforce the idea that you should have **one engine** per application, and **multiple sessions**, one per each group of operations.
|
||||
|
||||
///
|
||||
But it allows me to show you how they could be separated and to reinforce the idea that you should have **one engine** per application, and **multiple sessions**, one per each group of operations.
|
||||
|
||||
## Get a List of `Hero` Objects
|
||||
|
||||
@ -585,20 +386,6 @@ But for different reasons you might want to have the full **list of `Hero`** obj
|
||||
|
||||
The special `results` object also has a method `results.all()` that returns a list with all the objects:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="7"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/select/tutorial003_py310.py[ln:34-39]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="7"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -607,27 +394,14 @@ The special `results` object also has a method `results.all()` that returns a li
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial003.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
With this now we have all the heroes in a list in the `heroes` variable.
|
||||
|
||||
@ -641,11 +415,8 @@ After printing it, we would see something like:
|
||||
]
|
||||
```
|
||||
|
||||
/// info
|
||||
|
||||
It would actually look more compact, I'm formatting it a bit for you to see that it is actually a list with all the data.
|
||||
|
||||
///
|
||||
!!! info
|
||||
It would actually look more compact, I'm formatting it a bit for you to see that it is actually a list with all the data.
|
||||
|
||||
## Compact Version
|
||||
|
||||
@ -653,20 +424,6 @@ I have been creating several variables to be able to explain to you what each th
|
||||
|
||||
But knowing what is each object and what it is all doing, we can simplify it a bit and put it in a more compact form:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/select/tutorial004_py310.py[ln:34-37]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -675,27 +432,14 @@ But knowing what is each object and what it is all doing, we can simplify it a b
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial004.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Here we are putting it all on a single line, you will probably put the select statements in a single line like this more often.
|
||||
|
||||
@ -713,15 +457,12 @@ In this chapter we are touching some of them.
|
||||
|
||||
When importing from `sqlmodel` the `select()` function, you are using **SQLModel**'s version of `select`.
|
||||
|
||||
SQLAchemy also has its own `select`, and SQLModel's `select` uses SQLAlchemy's `select` internally.
|
||||
SQLAchemy also has it's own `select`, and SQLModel's `select` uses SQLAlchemy's `select` internally.
|
||||
|
||||
But SQLModel's version does a lot of **tricks** with type annotations to make sure you get the best **editor support** possible, no matter if you use **VS Code**, **PyCharm**, or something else. ✨
|
||||
|
||||
/// info
|
||||
|
||||
There was a lot of work and research, with different versions of the internal code, to improve this as much as possible. 🤓
|
||||
|
||||
///
|
||||
!!! info
|
||||
There was a lot of work and research, with different versions of the internal code, to improve this as much as possible. 🤓
|
||||
|
||||
### SQLModel's `session.exec`
|
||||
|
||||
@ -751,13 +492,10 @@ On top of that, **SQLModel**'s `session.exec()` also does some tricks to reduce
|
||||
|
||||
But SQLModel's `Session` still has access to `session.execute()` too.
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
Your editor will give you autocompletion for both `session.exec()` and `session.execute()`.
|
||||
|
||||
Your editor will give you autocompletion for both `session.exec()` and `session.execute()`.
|
||||
|
||||
📢 Remember to **always use `session.exec()`** to get the best editor support and developer experience.
|
||||
|
||||
///
|
||||
📢 Remember to **always use `session.exec()`** to get the best editor support and developer experience.
|
||||
|
||||
### Caveats of **SQLModel** Flavor
|
||||
|
||||
|
||||
@ -6,25 +6,14 @@ Now let's see how to update data using **SQLModel**.
|
||||
|
||||
As before, we'll continue from where we left off with the previous code.
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/indexes/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/indexes/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Remember to remove the `database.db` file before running the examples to get the same results.
|
||||
|
||||
@ -52,15 +41,12 @@ And the second part, with the `WHERE`, defines to which rows it should apply tha
|
||||
|
||||
In this case, as we only have one hero with the name `"Spider-Boy"`, it will only apply the update in that row.
|
||||
|
||||
/// info
|
||||
!!! info
|
||||
Notice that in the `UPDATE` the single equals sign (`=`) means **assignment**, setting a column to some value.
|
||||
|
||||
Notice that in the `UPDATE` the single equals sign (`=`) means **assignment**, setting a column to some value.
|
||||
And in the `WHERE` the same single equals sign (`=`) is used for **comparison** between two values, to find rows that match.
|
||||
|
||||
And in the `WHERE` the same single equals sign (`=`) is used for **comparison** between two values, to find rows that match.
|
||||
|
||||
This is in contrast to Python and most programming languages, where a single equals sign (`=`) is used for assignment, and two equal signs (`==`) are used for comparisons.
|
||||
|
||||
///
|
||||
This is in contrast to Python and most programming languages, where a single equals sign (`=`) is used for assignment, and two equal signs (`==`) are used for comparisons.
|
||||
|
||||
You can try that in **DB Browser for SQLite**:
|
||||
|
||||
@ -83,19 +69,16 @@ After that update, the data in the table will look like this, with the new age f
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
It will probably be more common to find the row to update by `id`, for example:
|
||||
|
||||
It will probably be more common to find the row to update by `id`, for example:
|
||||
```SQL
|
||||
UPDATE hero
|
||||
SET age=16
|
||||
WHERE id = 2
|
||||
```
|
||||
|
||||
```SQL
|
||||
UPDATE hero
|
||||
SET age=16
|
||||
WHERE id = 2
|
||||
```
|
||||
|
||||
But in the example above I used `name` to make it more intuitive.
|
||||
|
||||
///
|
||||
But in the example above I used `name` to make it more intuitive.
|
||||
|
||||
Now let's do the same update in code, with **SQLModel**.
|
||||
|
||||
@ -105,20 +88,6 @@ To get the same results, delete the `database.db` file before running the exampl
|
||||
|
||||
We'll start by selecting the hero `"Spider-Boy"`, this is the one we will update:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/update/tutorial001_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -127,69 +96,31 @@ We'll start by selecting the hero `"Spider-Boy"`, this is the one we will update
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/update/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/update/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Let's not forget to add that `update_heroes()` function to the `main()` function so that we call it when executing the program from the command line:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="6"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/update/tutorial001_py310.py[ln:56-63]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="6"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/update/tutorial001.py[ln:58-65]!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/update/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/update/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Up to that point, running that in the command line will output:
|
||||
|
||||
@ -212,11 +143,8 @@ Hero: name='Spider-Boy' secret_name='Pedro Parqueador' age=None id=2
|
||||
|
||||
</div>
|
||||
|
||||
/// tip
|
||||
|
||||
Notice that by this point, the hero still doesn't have an age.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Notice that by this point, the hero still doesn't have an age.
|
||||
|
||||
## Set a Field Value
|
||||
|
||||
@ -224,20 +152,6 @@ Now that you have a `hero` object, you can simply set the value of the field (th
|
||||
|
||||
In this case, we will set the `age` to `16`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="10"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/update/tutorial001_py310.py[ln:42-49]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="10"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -246,27 +160,14 @@ In this case, we will set the `age` to `16`:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/update/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/update/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Add the Hero to the Session
|
||||
|
||||
@ -274,20 +175,6 @@ Now that the hero object in memory has a change, in this case a new value for th
|
||||
|
||||
This is the same we did when creating new hero instances:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="11"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/update/tutorial001_py310.py[ln:42-50]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="11"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -296,27 +183,14 @@ This is the same we did when creating new hero instances:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/update/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/update/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Commit the Session
|
||||
|
||||
@ -324,20 +198,6 @@ To save the current changes in the session, **commit** it.
|
||||
|
||||
This will save the updated hero in the database:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="12"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/update/tutorial001_py310.py[ln:42-51]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="12"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -346,27 +206,14 @@ This will save the updated hero in the database:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/update/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/update/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
It will also save anything else that was added to the session.
|
||||
|
||||
@ -399,20 +246,6 @@ The data in the object would be automatically refreshed if we accessed an attrib
|
||||
|
||||
But in this example we are not accessing any attribute, we will only print the object. And we also want to be explicit, so we will `.refresh()` the object directly:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="13"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/update/tutorial001_py310.py[ln:42-52]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="13"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -421,27 +254,14 @@ But in this example we are not accessing any attribute, we will only print the o
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/update/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/update/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This refresh will trigger the same SQL query that would be automatically triggered by accessing an attribute. So it will generate this output:
|
||||
|
||||
@ -467,20 +287,6 @@ INFO Engine [generated in 0.00018s] (2,)
|
||||
|
||||
Now we can just print the hero:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="14"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/update/tutorial001_py310.py[ln:42-53]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="14"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -489,27 +295,14 @@ Now we can just print the hero:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/update/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/update/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Because we refreshed it right after updating it, it has fresh data, including the new `age` we just updated.
|
||||
|
||||
@ -534,31 +327,14 @@ Updated hero: name='Spider-Boy' secret_name='Pedro Parqueador' age=16 id=2
|
||||
|
||||
Now let's review all that code:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```{ .python .annotate hl_lines="42-53" }
|
||||
{!./docs_src/tutorial/update/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
{!./docs_src/tutorial/update/annotations/en/tutorial002.md!}
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```{ .python .annotate hl_lines="44-55" }
|
||||
{!./docs_src/tutorial/update/tutorial002.py!}
|
||||
```
|
||||
|
||||
{!./docs_src/tutorial/update/annotations/en/tutorial002.md!}
|
||||
|
||||
////
|
||||
|
||||
/// tip
|
||||
|
||||
Check out the number bubbles to see what is done by each line of code.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Check out the number bubbles to see what is done by each line of code.
|
||||
|
||||
## Multiple Updates
|
||||
|
||||
@ -566,22 +342,6 @@ The update process with **SQLModel** is more or less the same as with creating n
|
||||
|
||||
This also means that you can update several fields (attributes, columns) at once, and you can also update several objects (heroes) at once:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```{ .python .annotate hl_lines="15-17 19-21 23" }
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/update/tutorial004_py310.py[ln:42-68]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
{!./docs_src/tutorial/update/annotations/en/tutorial004.md!}
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```{ .python .annotate hl_lines="15-17 19-21 23" }
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -592,33 +352,17 @@ This also means that you can update several fields (attributes, columns) at once
|
||||
|
||||
{!./docs_src/tutorial/update/annotations/en/tutorial004.md!}
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/update/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/update/tutorial004.py!}
|
||||
```
|
||||
|
||||
////
|
||||
</details>
|
||||
|
||||
///
|
||||
|
||||
/// tip
|
||||
|
||||
Review what each line does by clicking each number bubble in the code. 👆
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Review what each line does by clicking each number bubble in the code. 👆
|
||||
|
||||
## Recap
|
||||
|
||||
|
||||
@ -31,25 +31,14 @@ We'll continue with the same examples we have been using in the previous chapter
|
||||
|
||||
And now we will update `select_heroes()` to filter the data.
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="36-41"
|
||||
{!./docs_src/tutorial/select/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python hl_lines="36-41"
|
||||
{!./docs_src/tutorial/select/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
If you already executed the previous examples and have a database with data, **remove the database file** before running each example, that way you won't have duplicate data and you will be able to get the same results.
|
||||
|
||||
@ -92,13 +81,10 @@ Then the database will bring a table like this:
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
Even if the result is only one row, the database always returns a **table**.
|
||||
|
||||
Even if the result is only one row, the database always returns a **table**.
|
||||
|
||||
In this case, a table with only one row.
|
||||
|
||||
///
|
||||
In this case, a table with only one row.
|
||||
|
||||
You can try that out in **DB Browser for SQLite**:
|
||||
|
||||
@ -201,20 +187,6 @@ Let's review some of the code we used to read data with **SQLModel**.
|
||||
|
||||
We care specially about the **select** statement:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/select/tutorial001_py310.py[ln:34-39]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -223,46 +195,19 @@ We care specially about the **select** statement:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/select/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
## Filter Rows Using `WHERE` with **SQLModel**
|
||||
|
||||
Now, the same way that we add `WHERE` to a SQL statement to filter rows, we can add a `.where()` to a **SQLModel** `select()` statement to filter rows, which will filter the objects returned:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/where/tutorial001_py310.py[ln:34-39]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -271,27 +216,14 @@ Now, the same way that we add `WHERE` to a SQL statement to filter rows, we can
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
It's a very small change, but it's packed of details. Let's explore them.
|
||||
|
||||
@ -336,13 +268,10 @@ So, what's happening there?
|
||||
|
||||
In the example above we are using two equal signs (`==`). That's called the "**equality operator**".
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
An **operator** is just a symbol that is put beside one value or in the middle of two values to do something with them.
|
||||
|
||||
An **operator** is just a symbol that is put beside one value or in the middle of two values to do something with them.
|
||||
|
||||
`==` is called the **equality** operator because it checks if two things are **equal**.
|
||||
|
||||
///
|
||||
`==` is called the **equality** operator because it checks if two things are **equal**.
|
||||
|
||||
When writing Python, if you write something using this equality operator (`==`) like:
|
||||
|
||||
@ -362,11 +291,8 @@ True
|
||||
False
|
||||
```
|
||||
|
||||
/// tip
|
||||
|
||||
`<`, `>`, `==`, `>=`, `<=`, and `!=` are all **operators** used for **comparisons**.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
`<`, `>`, `==`, `>=`, `<=`, and `!=` are all **operators** used for **comparisons**.
|
||||
|
||||
But SQLAlchemy adds some magic to the columns/fields in a **model class** to make those Python comparisons have super powers.
|
||||
|
||||
@ -525,11 +451,8 @@ select(Hero).where(Hero.secret_name == "Pedro Parqueador")
|
||||
|
||||
I think that alone, having better editor support, autocompletion, and inline errors, is enough to make it worth having expressions instead of keyword arguments. ✨
|
||||
|
||||
/// tip
|
||||
|
||||
**Expressions** also provide more features for other types of comparisons, shown down below. 👇
|
||||
|
||||
///
|
||||
!!! tip
|
||||
**Expressions** also provide more features for other types of comparisons, shown down below. 👇
|
||||
|
||||
## Exec the Statement
|
||||
|
||||
@ -537,20 +460,6 @@ Now that we know how `.where()` works, let's finish the code.
|
||||
|
||||
It's actually the same as in previous chapters for selecting data:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="6-8"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/where/tutorial001_py310.py[ln:34-39]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="6-8"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -559,27 +468,14 @@ It's actually the same as in previous chapters for selecting data:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial001_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial001.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
We take that statement, that now includes a `WHERE`, and we `exec()` it to get the results.
|
||||
|
||||
@ -606,15 +502,12 @@ secret_name='Dive Wilson' age=None id=1 name='Deadpond'
|
||||
</div>
|
||||
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
The `results` object is an iterable to be used in a `for` loop.
|
||||
|
||||
The `results` object is an iterable to be used in a `for` loop.
|
||||
Even if we got only one row, we iterate over that `results` object. Just as if it was a list of one element.
|
||||
|
||||
Even if we got only one row, we iterate over that `results` object. Just as if it was a list of one element.
|
||||
|
||||
We'll see other ways to get the data later.
|
||||
|
||||
///
|
||||
We'll see other ways to get the data later.
|
||||
|
||||
## Other Comparisons
|
||||
|
||||
@ -628,20 +521,6 @@ But we can use other standard Python comparisons. ✨
|
||||
|
||||
We could get the rows where a column is **not** equal to a value using `!=`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/where/tutorial002_py310.py[ln:34-39]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -650,27 +529,14 @@ We could get the rows where a column is **not** equal to a value using `!=`:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial002_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial002.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
That would output:
|
||||
|
||||
@ -683,20 +549,6 @@ secret_name='Tommy Sharp' age=48 id=3 name='Rusty-Man'
|
||||
|
||||
Let's update the function `create_heroes()` and add some more rows to make the next comparison examples clearer:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="4-10 13-19"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/where/tutorial003_py310.py[ln:21-39]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="4-10 13-19"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -705,27 +557,14 @@ Let's update the function `create_heroes()` and add some more rows to make the n
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial003.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Now that we have several heroes with different ages, it's gonna be more obvious what the next comparisons do.
|
||||
|
||||
@ -733,20 +572,6 @@ Now that we have several heroes with different ages, it's gonna be more obvious
|
||||
|
||||
Now let's use `>` to get the rows where a column is **more than** a value:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/where/tutorial003_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -755,27 +580,14 @@ Now let's use `>` to get the rows where a column is **more than** a value:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial003_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial003.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
That would output:
|
||||
|
||||
@ -785,30 +597,13 @@ age=36 id=6 name='Dr. Weird' secret_name='Steve Weird'
|
||||
age=93 id=7 name='Captain North America' secret_name='Esteban Rogelios'
|
||||
```
|
||||
|
||||
/// tip
|
||||
|
||||
Notice that it didn't select `Black Lion`, because the age is not *strictly* greater than `35`.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
Notice that it didn't select `Black Lion`, because the age is not *strictly* greater than `35`.
|
||||
|
||||
### More Than or Equal
|
||||
|
||||
Let's do that again, but with `>=` to get the rows where a column is **more than or equal** to a value:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/where/tutorial004_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -817,27 +612,14 @@ Let's do that again, but with `>=` to get the rows where a column is **more than
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial004_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial004.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
Because we are using `>=`, the age `35` will be included in the output:
|
||||
|
||||
@ -848,30 +630,13 @@ age=36 id=6 name='Dr. Weird' secret_name='Steve Weird'
|
||||
age=93 id=7 name='Captain North America' secret_name='Esteban Rogelios'
|
||||
```
|
||||
|
||||
/// tip
|
||||
|
||||
This time we got `Black Lion` too because although the age is not *strictly* greater than `35`it is *equal* to `35`.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
This time we got `Black Lion` too because although the age is not *strictly* greater than `35`it is *equal* to `35`.
|
||||
|
||||
### Less Than
|
||||
|
||||
Similarly, we can use `<` to get the rows where a column is **less than** a value:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/where/tutorial005_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -880,27 +645,14 @@ Similarly, we can use `<` to get the rows where a column is **less than** a valu
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial005_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial005.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
And we get the younger one with an age in the database:
|
||||
|
||||
@ -908,30 +660,13 @@ And we get the younger one with an age in the database:
|
||||
age=32 id=4 name='Tarantula' secret_name='Natalia Roman-on'
|
||||
```
|
||||
|
||||
/// tip
|
||||
|
||||
We could imagine that **Spider-Boy** is even **younger**. But because we don't know the age, it is `NULL` in the database (`None` in Python), it doesn't match any of these age comparisons with numbers.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
We could imagine that **Spider-Boy** is even **younger**. But because we don't know the age, it is `NULL` in the database (`None` in Python), it doesn't match any of these age comparisons with numbers.
|
||||
|
||||
### Less Than or Equal
|
||||
|
||||
Finally, we can use `<=` to get the rows where a column is **less than or equal** to a value:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/where/tutorial006_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -940,27 +675,14 @@ Finally, we can use `<=` to get the rows where a column is **less than or equal*
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial006_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial006.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
And we get the younger ones, `35` and below:
|
||||
|
||||
@ -969,11 +691,8 @@ age=32 id=4 name='Tarantula' secret_name='Natalia Roman-on'
|
||||
age=35 id=5 name='Black Lion' secret_name='Trevor Challa'
|
||||
```
|
||||
|
||||
/// tip
|
||||
|
||||
We get `Black Lion` here too because although the age is not *strictly* less than `35` it is *equal* to `35`.
|
||||
|
||||
///
|
||||
!!! tip
|
||||
We get `Black Lion` here too because although the age is not *strictly* less than `35` it is *equal* to `35`.
|
||||
|
||||
### Benefits of Expressions
|
||||
|
||||
@ -985,20 +704,6 @@ We can use the same standard Python comparison operators like `<`, `<=`, `>`, `>
|
||||
|
||||
Because `.where()` returns the same special select object back, we can add more `.where()` calls to it:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/where/tutorial007_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -1007,27 +712,14 @@ Because `.where()` returns the same special select object back, we can add more
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial007_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial007.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This will select the rows `WHERE` the `age` is **greater than or equal** to `35`, `AND` also the `age` is **less than** `40`.
|
||||
|
||||
@ -1068,20 +760,6 @@ age=36 id=6 name='Dr. Weird' secret_name='Steve Weird'
|
||||
|
||||
As an alternative to using multiple `.where()` we can also pass several expressions to a single `.where()`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/where/tutorial008_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -1090,27 +768,14 @@ As an alternative to using multiple `.where()` we can also pass several expressi
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial008_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial008.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
This is the same as the above, and will result in the same output with the two heroes:
|
||||
|
||||
@ -1127,64 +792,25 @@ But we can also combine expressions using `OR`. Which means that **any** (but no
|
||||
|
||||
To do it, you can import `or_`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!./docs_src/tutorial/where/tutorial009_py310.py[ln:1]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!./docs_src/tutorial/where/tutorial009.py[ln:1-3]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial009_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial009.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
And then pass both expressions to `or_()` and put it inside `.where()`.
|
||||
|
||||
For example, here we select the heroes that are the youngest OR the oldest:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/where/tutorial009_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -1193,27 +819,14 @@ For example, here we select the heroes that are the youngest OR the oldest:
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial009_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial009.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
When we run it, this generates the output:
|
||||
|
||||
@ -1250,7 +863,7 @@ It would be an error telling you that
|
||||
|
||||
> `Hero.age` is potentially `None`, and you cannot compare `None` with `>`
|
||||
|
||||
This is because as we are using pure and plain Python annotations for the fields, `age` is indeed annotated as `int | None (or Optional[int])`.
|
||||
This is because as we are using pure and plain Python annotations for the fields, `age` is indeed annotated as `Optional[int]`, which means `int` or `None`.
|
||||
|
||||
By using this simple and standard Python type annotations we get the benefit of the extra simplicity and the inline error checks when creating or using instances. ✨
|
||||
|
||||
@ -1264,62 +877,23 @@ We can tell the editor that this class attribute is actually a special **SQLMode
|
||||
|
||||
To do that, we can import `col()` (as short for "column"):
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="1"
|
||||
{!./docs_src/tutorial/where/tutorial011_py310.py[ln:1]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="3"
|
||||
{!./docs_src/tutorial/where/tutorial011.py[ln:1-3]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial011_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial011.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
And then put the **class attribute** inside `col()` when using it in a `.where()`:
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
{!./docs_src/tutorial/where/tutorial011_py310.py[ln:42-47]!}
|
||||
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
|
||||
```Python hl_lines="5"
|
||||
# Code above omitted 👆
|
||||
|
||||
@ -1328,27 +902,14 @@ And then put the **class attribute** inside `col()` when using it in a `.where()
|
||||
# Code below omitted 👇
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
/// details | 👀 Full file preview
|
||||
|
||||
//// tab | Python 3.10+
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial011_py310.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
//// tab | Python 3.7+
|
||||
<details>
|
||||
<summary>👀 Full file preview</summary>
|
||||
|
||||
```Python
|
||||
{!./docs_src/tutorial/where/tutorial011.py!}
|
||||
```
|
||||
|
||||
////
|
||||
|
||||
///
|
||||
</details>
|
||||
|
||||
So, now the comparison is not:
|
||||
|
||||
@ -1364,13 +925,10 @@ col(Hero.age) > 35
|
||||
|
||||
And with that the editor knows this code is actually fine, because this is a special **SQLModel** column.
|
||||
|
||||
/// tip
|
||||
!!! tip
|
||||
That `col()` will come handy later, giving autocompletion to several other things we can do with these special **class attributes** for columns.
|
||||
|
||||
That `col()` will come handy later, giving autocompletion to several other things we can do with these special **class attributes** for columns.
|
||||
|
||||
But we'll get there later.
|
||||
|
||||
///
|
||||
But we'll get there later.
|
||||
|
||||
## Recap
|
||||
|
||||
|
||||
@ -1,844 +0,0 @@
|
||||
# Virtual Environments
|
||||
|
||||
When you work in Python projects you probably should use a **virtual environment** (or a similar mechanism) to isolate the packages you install for each project.
|
||||
|
||||
/// info
|
||||
|
||||
If you already know about virtual environments, how to create them and use them, you might want to skip this section. 🤓
|
||||
|
||||
///
|
||||
|
||||
/// tip
|
||||
|
||||
A **virtual environment** is different than an **environment variable**.
|
||||
|
||||
An **environment variable** is a variable in the system that can be used by programs.
|
||||
|
||||
A **virtual environment** is a directory with some files in it.
|
||||
|
||||
///
|
||||
|
||||
/// info
|
||||
|
||||
This page will teach you how to use **virtual environments** and how they work.
|
||||
|
||||
If you are ready to adopt a **tool that manages everything** for you (including installing Python), try <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">uv</a>.
|
||||
|
||||
///
|
||||
|
||||
## Create a Project
|
||||
|
||||
First, create a directory for your project.
|
||||
|
||||
What I normally do is that I create a directory named `code` inside my home/user directory.
|
||||
|
||||
And inside of that I create one directory per project.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Go to the home directory
|
||||
$ cd
|
||||
// Create a directory for all your code projects
|
||||
$ mkdir code
|
||||
// Enter into that code directory
|
||||
$ cd code
|
||||
// Create a directory for this project
|
||||
$ mkdir awesome-project
|
||||
// Enter into that project directory
|
||||
$ cd awesome-project
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## Create a Virtual Environment
|
||||
|
||||
When you start working on a Python project **for the first time**, create a virtual environment **<abbr title="there are other options, this is a simple guideline">inside your project</abbr>**.
|
||||
|
||||
/// tip
|
||||
|
||||
You only need to do this **once per project**, not every time you work.
|
||||
|
||||
///
|
||||
|
||||
//// tab | `venv`
|
||||
|
||||
To create a virtual environment, you can use the `venv` module that comes with Python.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ python -m venv .venv
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
/// details | What that command means
|
||||
|
||||
* `python`: use the program called `python`
|
||||
* `-m`: call a module as a script, we'll tell it which module next
|
||||
* `venv`: use the module called `venv` that normally comes installed with Python
|
||||
* `.venv`: create the virtual environment in the new directory `.venv`
|
||||
|
||||
///
|
||||
|
||||
////
|
||||
|
||||
//// tab | `uv`
|
||||
|
||||
If you have <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a> installed, you can use it to create a virtual environment.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uv venv
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
/// tip
|
||||
|
||||
By default, `uv` will create a virtual environment in a directory called `.venv`.
|
||||
|
||||
But you could customize it passing an additional argument with the directory name.
|
||||
|
||||
///
|
||||
|
||||
////
|
||||
|
||||
That command creates a new virtual environment in a directory called `.venv`.
|
||||
|
||||
/// details | `.venv` or other name
|
||||
|
||||
You could create the virtual environment in a different directory, but there's a convention of calling it `.venv`.
|
||||
|
||||
///
|
||||
|
||||
## Activate the Virtual Environment
|
||||
|
||||
Activate the new virtual environment so that any Python command you run or package you install uses it.
|
||||
|
||||
/// tip
|
||||
|
||||
Do this **every time** you start a **new terminal session** to work on the project.
|
||||
|
||||
///
|
||||
|
||||
//// tab | Linux, macOS
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ source .venv/bin/activate
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows PowerShell
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ .venv\Scripts\Activate.ps1
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows Bash
|
||||
|
||||
Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ source .venv/Scripts/activate
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
/// tip
|
||||
|
||||
Every time you install a **new package** in that environment, **activate** the environment again.
|
||||
|
||||
This makes sure that if you use a **terminal (<abbr title="command line interface">CLI</abbr>) program** installed by that package, you use the one from your virtual environment and not any other that could be installed globally, probably with a different version than what you need.
|
||||
|
||||
///
|
||||
|
||||
## Check the Virtual Environment is Active
|
||||
|
||||
Check that the virtual environment is active (the previous command worked).
|
||||
|
||||
/// tip
|
||||
|
||||
This is **optional**, but it's a good way to **check** that everything is working as expected and you are using the virtual environment you intended.
|
||||
|
||||
///
|
||||
|
||||
//// tab | Linux, macOS, Windows Bash
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ which python
|
||||
|
||||
/home/user/code/awesome-project/.venv/bin/python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
If it shows the `python` binary at `.venv/bin/python`, inside of your project (in this case `awesome-project`), then it worked. 🎉
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows PowerShell
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ Get-Command python
|
||||
|
||||
C:\Users\user\code\awesome-project\.venv\Scripts\python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
If it shows the `python` binary at `.venv\Scripts\python`, inside of your project (in this case `awesome-project`), then it worked. 🎉
|
||||
|
||||
////
|
||||
|
||||
## Upgrade `pip`
|
||||
|
||||
/// tip
|
||||
|
||||
If you use <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a> you would use it to install things instead of `pip`, so you don't need to upgrade `pip`. 😎
|
||||
|
||||
///
|
||||
|
||||
If you are using `pip` to install packages (it comes by default with Python), you should **upgrade** it to the latest version.
|
||||
|
||||
Many exotic errors while installing a package are solved by just upgrading `pip` first.
|
||||
|
||||
/// tip
|
||||
|
||||
You would normally do this **once**, right after you create the virtual environment.
|
||||
|
||||
///
|
||||
|
||||
Make sure the virtual environment is active (with the command above) and then run:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ python -m pip install --upgrade pip
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## Add `.gitignore`
|
||||
|
||||
If you are using **Git** (you should), add a `.gitignore` file to exclude everything in your `.venv` from Git.
|
||||
|
||||
/// tip
|
||||
|
||||
If you used <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a> to create the virtual environment, it already did this for you, you can skip this step. 😎
|
||||
|
||||
///
|
||||
|
||||
/// tip
|
||||
|
||||
Do this **once**, right after you create the virtual environment.
|
||||
|
||||
///
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ echo "*" > .venv/.gitignore
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
/// details | What that command means
|
||||
|
||||
* `echo "*"`: will "print" the text `*` in the terminal (the next part changes that a bit)
|
||||
* `>`: anything printed to the terminal by the command to the left of `>` should not be printed but instead written to the file that goes to the right of `>`
|
||||
* `.gitignore`: the name of the file where the text should be written
|
||||
|
||||
And `*` for Git means "everything". So, it will ignore everything in the `.venv` directory.
|
||||
|
||||
That command will create a file `.gitignore` with the content:
|
||||
|
||||
```gitignore
|
||||
*
|
||||
```
|
||||
|
||||
///
|
||||
|
||||
## Install Packages
|
||||
|
||||
After activating the environment, you can install packages in it.
|
||||
|
||||
/// tip
|
||||
|
||||
Do this **once** when installing or upgrading the packages your project needs.
|
||||
|
||||
If you need to upgrade a version or add a new package you would **do this again**.
|
||||
|
||||
///
|
||||
|
||||
### Install Packages Directly
|
||||
|
||||
If you're in a hurry and don't want to use a file to declare your project's package requirements, you can install them directly.
|
||||
|
||||
/// tip
|
||||
|
||||
It's a (very) good idea to put the packages and versions your program needs in a file (for example `requirements.txt` or `pyproject.toml`).
|
||||
|
||||
///
|
||||
|
||||
//// tab | `pip`
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install sqlmodel
|
||||
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
//// tab | `uv`
|
||||
|
||||
If you have <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a>:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uv pip install sqlmodel
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
### Install from `requirements.txt`
|
||||
|
||||
If you have a `requirements.txt`, you can now use it to install its packages.
|
||||
|
||||
//// tab | `pip`
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install -r requirements.txt
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
//// tab | `uv`
|
||||
|
||||
If you have <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">`uv`</a>:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ uv pip install -r requirements.txt
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
/// details | `requirements.txt`
|
||||
|
||||
A `requirements.txt` with some packages could look like:
|
||||
|
||||
```requirements.txt
|
||||
sqlmodel==0.13.0
|
||||
rich==13.7.1
|
||||
```
|
||||
|
||||
///
|
||||
|
||||
## Run Your Program
|
||||
|
||||
After you activated the virtual environment, you can run your program, and it will use the Python inside of your virtual environment with the packages you installed there.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ python main.py
|
||||
|
||||
Hello World
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## Configure Your Editor
|
||||
|
||||
You would probably use an editor, make sure you configure it to use the same virtual environment you created (it will probably autodetect it) so that you can get autocompletion and inline errors.
|
||||
|
||||
For example:
|
||||
|
||||
* <a href="https://code.visualstudio.com/docs/python/environments#_select-and-activate-an-environment" class="external-link" target="_blank">VS Code</a>
|
||||
* <a href="https://www.jetbrains.com/help/pycharm/creating-virtual-environment.html" class="external-link" target="_blank">PyCharm</a>
|
||||
|
||||
/// tip
|
||||
|
||||
You normally have to do this only **once**, when you create the virtual environment.
|
||||
|
||||
///
|
||||
|
||||
## Deactivate the Virtual Environment
|
||||
|
||||
Once you are done working on your project you can **deactivate** the virtual environment.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ deactivate
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
This way, when you run `python` it won't try to run it from that virtual environment with the packages installed there.
|
||||
|
||||
## Ready to Work
|
||||
|
||||
Now you're ready to start working on your project.
|
||||
|
||||
|
||||
|
||||
/// tip
|
||||
|
||||
Do you want to understand what's all that above?
|
||||
|
||||
Continue reading. 👇🤓
|
||||
|
||||
///
|
||||
|
||||
## Why Virtual Environments
|
||||
|
||||
To work with SQLModel you need to install <a href="https://www.python.org/" class="external-link" target="_blank">Python</a>.
|
||||
|
||||
After that, you would need to **install** SQLModel and any other **packages** you want to use.
|
||||
|
||||
To install packages you would normally use the `pip` command that comes with Python (or similar alternatives).
|
||||
|
||||
Nevertheless, if you just use `pip` directly, the packages would be installed in your **global Python environment** (the global installation of Python).
|
||||
|
||||
### The Problem
|
||||
|
||||
So, what's the problem with installing packages in the global Python environment?
|
||||
|
||||
At some point, you will probably end up writing many different programs that depend on **different packages**. And some of these projects you work on will depend on **different versions** of the same package. 😱
|
||||
|
||||
For example, you could create a project called `philosophers-stone`, this program depends on another package called **`harry`, using the version `1`**. So, you need to install `harry`.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
stone(philosophers-stone) -->|requires| harry-1[harry v1]
|
||||
```
|
||||
|
||||
Then, at some point later, you create another project called `prisoner-of-azkaban`, and this project also depends on `harry`, but this project needs **`harry` version `3`**.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3]
|
||||
```
|
||||
|
||||
But now the problem is, if you install the packages globally (in the global environment) instead of in a local **virtual environment**, you will have to choose which version of `harry` to install.
|
||||
|
||||
If you want to run `philosophers-stone` you will need to first install `harry` version `1`, for example with:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install "harry==1"
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
And then you would end up with `harry` version `1` installed in your global Python environment.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph global[global env]
|
||||
harry-1[harry v1]
|
||||
end
|
||||
subgraph stone-project[philosophers-stone project]
|
||||
stone(philosophers-stone) -->|requires| harry-1
|
||||
end
|
||||
```
|
||||
|
||||
But then if you want to run `prisoner-of-azkaban`, you will need to uninstall `harry` version `1` and install `harry` version `3` (or just installing version `3` would automatically uninstall version `1`).
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ pip install "harry==3"
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
And then you would end up with `harry` version `3` installed in your global Python environment.
|
||||
|
||||
And if you try to run `philosophers-stone` again, there's a chance it would **not work** because it needs `harry` version `1`.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph global[global env]
|
||||
harry-1[<strike>harry v1</strike>]
|
||||
style harry-1 fill:#ccc,stroke-dasharray: 5 5
|
||||
harry-3[harry v3]
|
||||
end
|
||||
subgraph stone-project[philosophers-stone project]
|
||||
stone(philosophers-stone) -.-x|⛔️| harry-1
|
||||
end
|
||||
subgraph azkaban-project[prisoner-of-azkaban project]
|
||||
azkaban(prisoner-of-azkaban) --> |requires| harry-3
|
||||
end
|
||||
```
|
||||
|
||||
/// tip
|
||||
|
||||
It's very common in Python packages to try the best to **avoid breaking changes** in **new versions**, but it's better to be safe, and install newer versions intentionally and when you can run the tests to check everything is working correctly.
|
||||
|
||||
///
|
||||
|
||||
Now, imagine that with **many** other **packages** that all your **projects depend on**. That's very difficult to manage. And you would probably end up running some projects with some **incompatible versions** of the packages, and not knowing why something isn't working.
|
||||
|
||||
Also, depending on your operating system (e.g. Linux, Windows, macOS), it could have come with Python already installed. And in that case it probably had some packages pre-installed with some specific versions **needed by your system**. If you install packages in the global Python environment, you could end up **breaking** some of the programs that came with your operating system.
|
||||
|
||||
## Where are Packages Installed
|
||||
|
||||
When you install Python, it creates some directories with some files in your computer.
|
||||
|
||||
Some of these directories are the ones in charge of having all the packages you install.
|
||||
|
||||
When you run:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
// Don't run this now, it's just an example 🤓
|
||||
$ pip install sqlmodel
|
||||
---> 100%
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
That will download a compressed file with the SQLModel code, normally from <a href="https://pypi.org/project/sqlmodel/" class="external-link" target="_blank">PyPI</a>.
|
||||
|
||||
It will also **download** files for other packages that SQLModel depends on.
|
||||
|
||||
Then it will **extract** all those files and put them in a directory in your computer.
|
||||
|
||||
By default, it will put those files downloaded and extracted in the directory that comes with your Python installation, that's the **global environment**.
|
||||
|
||||
## What are Virtual Environments
|
||||
|
||||
The solution to the problems of having all the packages in the global environment is to use a **virtual environment for each project** you work on.
|
||||
|
||||
A virtual environment is a **directory**, very similar to the global one, where you can install the packages for a project.
|
||||
|
||||
This way, each project will have its own virtual environment (`.venv` directory) with its own packages.
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph stone-project[philosophers-stone project]
|
||||
stone(philosophers-stone) --->|requires| harry-1
|
||||
subgraph venv1[.venv]
|
||||
harry-1[harry v1]
|
||||
end
|
||||
end
|
||||
subgraph azkaban-project[prisoner-of-azkaban project]
|
||||
azkaban(prisoner-of-azkaban) --->|requires| harry-3
|
||||
subgraph venv2[.venv]
|
||||
harry-3[harry v3]
|
||||
end
|
||||
end
|
||||
stone-project ~~~ azkaban-project
|
||||
```
|
||||
|
||||
## What Does Activating a Virtual Environment Mean
|
||||
|
||||
When you activate a virtual environment, for example with:
|
||||
|
||||
//// tab | Linux, macOS
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ source .venv/bin/activate
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows PowerShell
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ .venv\Scripts\Activate.ps1
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows Bash
|
||||
|
||||
Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ source .venv/Scripts/activate
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
That command will create or modify some [environment variables](environment-variables.md){.internal-link target=_blank} that will be available for the next commands.
|
||||
|
||||
One of those variables is the `PATH` variable.
|
||||
|
||||
/// tip
|
||||
|
||||
You can learn more about the `PATH` environment variable in the [Environment Variables](environment-variables.md#path-environment-variable){.internal-link target=_blank} section.
|
||||
|
||||
///
|
||||
|
||||
Activating a virtual environment adds its path `.venv/bin` (on Linux and macOS) or `.venv\Scripts` (on Windows) to the `PATH` environment variable.
|
||||
|
||||
Let's say that before activating the environment, the `PATH` variable looked like this:
|
||||
|
||||
//// tab | Linux, macOS
|
||||
|
||||
```plaintext
|
||||
/usr/bin:/bin:/usr/sbin:/sbin
|
||||
```
|
||||
|
||||
That means that the system would look for programs in:
|
||||
|
||||
* `/usr/bin`
|
||||
* `/bin`
|
||||
* `/usr/sbin`
|
||||
* `/sbin`
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows
|
||||
|
||||
```plaintext
|
||||
C:\Windows\System32
|
||||
```
|
||||
|
||||
That means that the system would look for programs in:
|
||||
|
||||
* `C:\Windows\System32`
|
||||
|
||||
////
|
||||
|
||||
After activating the virtual environment, the `PATH` variable would look something like this:
|
||||
|
||||
//// tab | Linux, macOS
|
||||
|
||||
```plaintext
|
||||
/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin
|
||||
```
|
||||
|
||||
That means that the system will now start looking first look for programs in:
|
||||
|
||||
```plaintext
|
||||
/home/user/code/awesome-project/.venv/bin
|
||||
```
|
||||
|
||||
before looking in the other directories.
|
||||
|
||||
So, when you type `python` in the terminal, the system will find the Python program in
|
||||
|
||||
```plaintext
|
||||
/home/user/code/awesome-project/.venv/bin/python
|
||||
```
|
||||
|
||||
and use that one.
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows
|
||||
|
||||
```plaintext
|
||||
C:\Users\user\code\awesome-project\.venv\Scripts;C:\Windows\System32
|
||||
```
|
||||
|
||||
That means that the system will now start looking first look for programs in:
|
||||
|
||||
```plaintext
|
||||
C:\Users\user\code\awesome-project\.venv\Scripts
|
||||
```
|
||||
|
||||
before looking in the other directories.
|
||||
|
||||
So, when you type `python` in the terminal, the system will find the Python program in
|
||||
|
||||
```plaintext
|
||||
C:\Users\user\code\awesome-project\.venv\Scripts\python
|
||||
```
|
||||
|
||||
and use that one.
|
||||
|
||||
////
|
||||
|
||||
An important detail is that it will put the virtual environment path at the **beginning** of the `PATH` variable. The system will find it **before** finding any other Python available. This way, when you run `python`, it will use the Python **from the virtual environment** instead of any other `python` (for example, a `python` from a global environment).
|
||||
|
||||
Activating a virtual environment also changes a couple of other things, but this is one of the most important things it does.
|
||||
|
||||
## Checking a Virtual Environment
|
||||
|
||||
When you check if a virtual environment is active, for example with:
|
||||
|
||||
//// tab | Linux, macOS, Windows Bash
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ which python
|
||||
|
||||
/home/user/code/awesome-project/.venv/bin/python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
//// tab | Windows PowerShell
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ Get-Command python
|
||||
|
||||
C:\Users\user\code\awesome-project\.venv\Scripts\python
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
////
|
||||
|
||||
That means that the `python` program that will be used is the one **in the virtual environment**.
|
||||
|
||||
you use `which` in Linux and macOS and `Get-Command` in Windows PowerShell.
|
||||
|
||||
The way that command works is that it will go and check in the `PATH` environment variable, going through **each path in order**, looking for the program called `python`. Once it finds it, it will **show you the path** to that program.
|
||||
|
||||
The most important part is that when you call `python`, that is the exact "`python`" that will be executed.
|
||||
|
||||
So, you can confirm if you are in the correct virtual environment.
|
||||
|
||||
/// tip
|
||||
|
||||
It's easy to activate one virtual environment, get one Python, and then **go to another project**.
|
||||
|
||||
And the second project **wouldn't work** because you are using the **incorrect Python**, from a virtual environment for another project.
|
||||
|
||||
It's useful being able to check what `python` is being used. 🤓
|
||||
|
||||
///
|
||||
|
||||
## Why Deactivate a Virtual Environment
|
||||
|
||||
For example, you could be working on a project `philosophers-stone`, **activate that virtual environment**, install packages and work with that environment.
|
||||
|
||||
And then you want to work on **another project** `prisoner-of-azkaban`.
|
||||
|
||||
You go to that project:
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ cd ~/code/prisoner-of-azkaban
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
If you don't deactivate the virtual environment for `philosophers-stone`, when you run `python` in the terminal, it will try to use the Python from `philosophers-stone`.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ cd ~/code/prisoner-of-azkaban
|
||||
|
||||
$ python main.py
|
||||
|
||||
// Error importing sirius, it's not installed 😱
|
||||
Traceback (most recent call last):
|
||||
File "main.py", line 1, in <module>
|
||||
import sirius
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
But if you deactivate the virtual environment and activate the new one for `prisoner-of-askaban` then when you run `python` it will use the Python from the virtual environment in `prisoner-of-azkaban`.
|
||||
|
||||
<div class="termy">
|
||||
|
||||
```console
|
||||
$ cd ~/code/prisoner-of-azkaban
|
||||
|
||||
// You don't need to be in the old directory to deactivate, you can do it wherever you are, even after going to the other project 😎
|
||||
$ deactivate
|
||||
|
||||
// Activate the virtual environment in prisoner-of-azkaban/.venv 🚀
|
||||
$ source .venv/bin/activate
|
||||
|
||||
// Now when you run python, it will find the package sirius installed in this virtual environment ✨
|
||||
$ python main.py
|
||||
|
||||
I solemnly swear 🐺
|
||||
```
|
||||
|
||||
</div>
|
||||
|
||||
## Alternatives
|
||||
|
||||
This is a simple guide to get you started and teach you how everything works **underneath**.
|
||||
|
||||
There are many **alternatives** to managing virtual environments, package dependencies (requirements), projects.
|
||||
|
||||
Once you are ready and want to use a tool to **manage the entire project**, packages dependencies, virtual environments, etc. I would suggest you try <a href="https://github.com/astral-sh/uv" class="external-link" target="_blank">uv</a>.
|
||||
|
||||
`uv` can do a lot of things, it can:
|
||||
|
||||
* **Install Python** for you, including different versions
|
||||
* Manage the **virtual environment** for your projects
|
||||
* Install **packages**
|
||||
* Manage package **dependencies and versions** for your project
|
||||
* Make sure you have an **exact** set of packages and versions to install, including their dependencies, so that you can be sure that you can run your project in production exactly the same as in your computer while developing, this is called **locking**
|
||||
* And many other things
|
||||
|
||||
## Conclusion
|
||||
|
||||
If you read and understood all this, now **you know much more** about virtual environments than many developers out there. 🤓
|
||||
|
||||
Knowing these details will most probably be useful in a future time when you are debugging something that seems complex, but you will know **how it all works underneath**. 😎
|
||||