本文へスキップ
製品デスクトップツールTASTECAD図面の確認TASTEFILESファイル管理TASTEFTPファイル転送TASTESSHリモートワークスペースTASTEZIP圧縮と展開TASTEWINMファイル管理開発ツールTASTECODERust 統合開発環境TASTESTUDIO統合開発・テスト環境TASTEETLデータ統合(ETL)サーバーTASTEREMOTEリモートデスクトップサーバーTASTEGEO空間情報サーバーTASTEMAILメールワークスペース投資TASTESTOCK株式自動売買デスクトップアプリはじめるダウンロードドキュメント購入すべての製品
マーケットプレイス
ニュース
技術ニュース今日の開発ニュース開発ドキュメントプログラミング言語RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWebフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngularサーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Expressアプリ・デスクトップ フレームワークTauriFlutterReact NativeElectronアルゴリズムアルゴリズムの基礎主要アルゴリズム発展アルゴリズム実務のアルゴリズム
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケースコミュニティガイド
協業技術移転ウェブサイト構築デスクトップアプリ構築リリース・決済パイプライン販売パートナーお問い合わせ
サービスリモートデスクトップインストールパッケージのカスタマイズ
TASTEDEV
製品

デスクトップツール

TASTECAD複雑な図面を、軽やかにひらくTASTEFILES必要なファイルだけを、最速でTASTEFTPファイルが行き交う、いちばん端正な道TASTESSHサーバーとあなたを、より確かにつなぐTASTEZIPより速くまとめ、より安全にひらくTASTEWINM2つの画面で整理する、キーボード中心のファイルマネージャー

開発ツール

TASTECODERust アプリの編集・ビルド・デバッグ・テストまでひとつのウィンドウでTASTESTUDIO編集からリモートテスト、承認した AI 修正までTASTEETL値を見ながら、データを運ぶ

サーバー

TASTEREMOTE自社サーバーで運用するリモートデスクトップTASTEGEOGeoServer 互換の空間情報サーバーを Rust で作り直しますTASTEMAILメールの主導権を、もう一度自分の手に

投資

TASTESTOCKいつ・何を。自分で決めたルールどおりに動く株式自動売買

はじめる

ダウンロード全製品の最新版ドキュメント各製品の使い方購入サブスクリプション・永久ライセンスすべての製品全製品を一覧で
すべての製品
マーケットプレイスニュース
技術

ニュース

今日の開発ニュース言語・フレームワーク・GitHub・AI の公式発表開発ドキュメント言語・フレームワーク・アルゴリズムのガイド

プログラミング言語

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

フレームワーク

Webフロントエンド フレームワークNext.jsReactVue.js · NuxtSvelteKitAngular
サーバー フレームワークSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
アプリ・デスクトップ フレームワークTauriFlutterReact NativeElectron

アルゴリズム

アルゴリズムの基礎計算量解析 · ソート · 探索 · 基本データ構造 · 木構造とヒープ主要アルゴリズムグラフ探索 · 最短経路と最小全域木 · 動的計画法 · 貪欲法 · 分割統治法 · バックトラッキング発展アルゴリズム文字列アルゴリズム · 数学と整数論 · ビット演算 · セグメント木 · Union-Find実務のアルゴリズムコーディング面接対策 · LRUキャッシュ · レート制限 · コンシステントハッシュ法
開発ドキュメントをすべて見る
コミュニティ
プロジェクトビルダーと作品を探す開発ログ決定と試行錯誤プロンプト再利用できる指示AIツールの問題Claude・Codex・Gemini の問題と回避策ショーケース完成した成果コミュニティガイドオープンにつくる方法
協業
技術移転Rust・egui でネイティブアプリを作るウェブサイト構築10言語、アカウント、ドキュメントとダウンロードデスクトップアプリ構築Rust・egui、WebView なしリリース・決済パイプライン署名・MSI・deb・rpm・AppImage・ハッシュ販売パートナー紹介して決済額の30%お問い合わせ構築・提携・投資のご相談
サービス
リモートデスクトップブラウザから自分のパソコンへインストールパッケージのカスタマイズ必要な機能だけ、設定は事前に
購入
JA
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
ログイン
ログイン
TASTEDEV

小さなツールから、より良い開発へ。

support@tastedev.netTASTEDEVを支援
製品製品ラインナップ購入ドキュメントダウンロードマーケットプレイスサポート
コミュニティプロジェクト開発ログプロンプトAIツールの問題ショーケース
ポリシー会社概要プライバシーポリシー利用規約サブスクリプション規約返金ポリシーコミュニティガイドライン
アカウントログイン新規登録
訪問者
今日
昨日
累計閲覧
商号
GXSOFT
代表者
CHOI YOUNG GU
事業者登録番号
853-44-00368
所在地
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
電話
+82-10-4404-1523
メール
whitecalvin@tastedev.net
個人情報保護責任者
CHOI YOUNG GU

© 2026 TASTEDEV製品情報は検証済みの開発ソースに基づいています。リリース・改善中

Django ドキュメント
Django
Getting Started with DjangoProject StructureCore ConceptsData and StateTestingDeployment
ディスカッション

Django ガイド · 4/6

Data and State

この章は現在、英語でのみ提供しています。

In Django you describe data with ORM models, apply them to the database with migrations, and read and write it through QuerySets. User input is validated with forms, and state that lasts across requests is handled by sessions and the authentication system.

Models and relationships

Each attribute on a model class becomes a column in its table. ForeignKey creates a many-to-one relationship, ManyToManyField a many-to-many one, and OneToOneField a one-to-one one.

# polls/models.py
from django.db import models
from django.utils import timezone


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField(default=timezone.now)

    class Meta:
        ordering = ["-pub_date"]

    def __str__(self):
        return self.question_text


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="choices")
    choice_text = models.CharField(max_length=200)
    votes = models.PositiveIntegerField(default=0)

on_delete decides what happens when the referenced row is deleted: CASCADE deletes this one too, PROTECT blocks it, and SET_NULL clears the field (needs null=True). related_name sets the name for the reverse lookup, as in question.choices.all().

Migrations

After changing your models, apply the change to the database in two steps.

# Detect model changes and write a file into migrations/
python manage.py makemigrations polls

# Show the SQL that will run
python manage.py sqlmigrate polls 0001

# Apply it to the database
python manage.py migrate

# List migrations and whether they are applied
python manage.py showmigrations

Commit migration files with your code so teammates and servers get the same schema from migrate. The default database is SQLite; production deployments often use PostgreSQL, and switching is a matter of changing DATABASES.

Querying with QuerySets

Model.objects is a manager, and the QuerySets it returns are lazy. Chaining filters runs no queries; the database is hit once, when you iterate over the QuerySet or turn it into a list.

from datetime import timedelta

from django.db.models import Count, F, Q
from django.utils import timezone

from polls.models import Choice, Question

# Create and save
q = Question.objects.create(question_text="What is your favorite language?")
q.choices.create(choice_text="Python")

# Filter with field__lookup syntax
recent = Question.objects.filter(pub_date__gte=timezone.now() - timedelta(days=7))
python_q = Question.objects.filter(question_text__icontains="python")

# Follow relations and annotate with a count
popular = (
    Question.objects.annotate(total=Count("choices"))
    .filter(total__gt=1)
    .order_by("-total")
)

# OR conditions and an atomic increment
Question.objects.filter(Q(question_text__startswith="Why") | Q(question_text__startswith="How"))
Choice.objects.filter(pk=1).update(votes=F("votes") + 1)

# Avoid N+1 queries
for choice in Choice.objects.select_related("question"):
    print(choice.question.question_text)
この章について質問がありますか?
前の章Core Concepts次の章Testing

select_related fetches foreign keys in the same query with a JOIN, while prefetch_related loads many-to-many and reverse relations with one extra query. Try queries in python manage.py shell, and wrap writes that must succeed or fail together in transaction.atomic().

Forms

A form takes input, validates it and hands back clean values in cleaned_data. When the fields match a model, ModelForm saves you most of the work.

# polls/forms.py
from django import forms

from .models import Question


class QuestionForm(forms.ModelForm):
    class Meta:
        model = Question
        fields = ["question_text"]

    def clean_question_text(self):
        text = self.cleaned_data["question_text"].strip()
        if not text.endswith("?"):
            raise forms.ValidationError("A question must end with a question mark.")
        return text
# polls/views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render

from .forms import QuestionForm


@login_required
def create(request):
    if request.method == "POST":
        form = QuestionForm(request.POST)
        if form.is_valid():
            question = form.save()
            return redirect("polls:detail", question_id=question.pk)
    else:
        form = QuestionForm()
    return render(request, "polls/create.html", {"form": form})

Every POST form needs {% csrf_token %} to pass the CSRF middleware. Redirecting after a save stops a refresh from resubmitting the data.

Sessions and authentication

Sessions keep per-visitor state on the server and store only a session ID cookie in the browser. In a view, request.session behaves like a dictionary.

def add_to_cart(request, item_id):
    cart = request.session.get("cart", [])
    cart.append(item_id)
    request.session["cart"] = cart
    return redirect("shop:cart")

The authentication system, django.contrib.auth, provides user, group and permission models plus views for login, logout and password changes. Adding path("accounts/", include("django.contrib.auth.urls")) gives you the standard auth URLs. In views, request.user is the current user, and @login_required or LoginRequiredMixin restricts access. For a new project, the official docs recommend creating a custom user model that subclasses AbstractUser and pointing AUTH_USER_MODEL at it from the start, because switching later is very hard.

Summary

  • Models map to tables, fields to columns, and ForeignKey and friends to relationships.
  • makemigrations records changes and migrate applies them.
  • QuerySets are lazy; select_related and prefetch_related cut down the number of queries.
  • Validate input with forms, and manage per-user state with sessions and django.contrib.auth.

コメント 0件

人気のコメント順新しい順

ログイン · ログインするとコメントできます。