Vai al contenuto principale
ProdottiStrumenti desktopTASTECADVisualizzazione disegniTASTEFILESGestione fileTASTEFTPTrasferimento fileTASTESSHSpazio di lavoro remotoTASTEZIPCompressione ed estrazioneTASTEWINMGestione fileStrumenti per sviluppatoriTASTECODEAmbiente di sviluppo integrato per RustTASTESTUDIOAmbiente integrato di sviluppo e testTASTEETLIntegrazione dati (ETL)ServerTASTEREMOTEServer di desktop remotoTASTEGEOServer geospazialeTASTEMAILSpazio di lavoro emailInvestimentiTASTESTOCKApp desktop di trading automatico azionarioIniziaDownloadDocumentazioneAcquistaTutti i prodotti
Marketplace
Notizie
TecnologiaNotizieNotizie di sviluppo di oggiDocumentazioneLinguaggi di programmazioneRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFramework frontend webNext.jsReactVue.js · NuxtSvelteKitAngularFramework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFramework per app e desktopTauriFlutterReact NativeElectronAlgoritmiBasi degli algoritmiAlgoritmi fondamentaliAlgoritmi avanzatiAlgoritmi pratici
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrinaGuida alla community
CollaboraTrasferimento tecnicoRealizzazione del sito webRealizzazione di app desktopPipeline di rilascio e pagamentoPartner commercialeContatti
ServiziDesktop remotoPacchetti di installazione su misura
TASTEDEV
Prodotti

Strumenti desktop

TASTECADApri con leggerezza anche i disegni più complessiTASTEFILESSolo i file che servono, alla massima velocitàTASTEFTPLa via più ordinata per i tuoi fileTASTESSHUn legame più solido tra te e i tuoi serverTASTEZIPComprimi più veloce, estrai più sicuroTASTEWINMUn file manager a due pannelli pensato per la tastiera

Strumenti per sviluppatori

TASTECODEModifica, compila, esegui il debug e testa app Rust in un'unica finestraTASTESTUDIODalla modifica ai test remoti e alle correzioni IA approvateTASTEETLSposta i dati guardando i valori

Server

TASTEREMOTEUn desktop remoto che gira sul tuo serverTASTEGEOUn server geospaziale compatibile con GeoServer, ricostruito in RustTASTEMAILRiprendi il controllo della tua posta

Investimenti

TASTESTOCKTrading automatico azionario secondo le regole che decidi tu: quando e che cosa

Inizia

DownloadUltime versioni di ogni prodottoDocsCome usare ogni prodottoAcquistaAbbonamenti e licenze perpetueTutti i prodottiTutti i prodotti a colpo d’occhio
Tutti i prodotti
MarketplaceNotizie
Tecnologia

Notizie

Notizie di sviluppo di oggiAnnunci ufficiali su linguaggi, framework, GitHub e IADocumentazioneGuide a linguaggi, framework e algoritmi

Linguaggi di programmazione

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Framework

Framework frontend webNext.jsReactVue.js · NuxtSvelteKitAngular
Framework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Framework per app e desktopTauriFlutterReact NativeElectron

Algoritmi

Basi degli algoritmiAnalisi della complessità · Ordinamento · Ricerca · Strutture dati di base · Alberi e heapAlgoritmi fondamentaliVisita dei grafi · Cammini minimi e alberi ricoprenti · Programmazione dinamica · Algoritmi greedy · Divide et impera · BacktrackingAlgoritmi avanzatiAlgoritmi sulle stringhe · Matematica e teoria dei numeri · Manipolazione dei bit · Alberi di segmenti · Union-FindAlgoritmi praticiStrategia per colloqui di programmazione · Cache LRU · Rate limiting · Hashing consistente
Tutta la documentazione di sviluppo
Community
ProgettiScopri sviluppatori e lavoriLog di sviluppoDecisioni e lezioni appresePromptIstruzioni riutilizzabiliProblemi degli strumenti di IAProblemi e alternative di Claude, Codex, GeminiVetrinaRisultati completatiGuida alla communityCome sviluppiamo in modo aperto
Collabora
Trasferimento tecnicoApp native in Rust ed eguiRealizzazione del sito web10 lingue, account, documentazione e downloadRealizzazione di app desktopRust ed egui, senza WebViewPipeline di rilascio e pagamentoFirma, MSI, deb, rpm, AppImage, hashPartner commercialeConsigliaci e ricevi il 30%ContattiSviluppo, partnership e investimenti
Servizi
Desktop remotoRaggiungi il tuo computer dal browserPacchetti di installazione su misuraSolo il necessario, impostazioni precaricate
Acquista
IT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Accedi
Accedi
TASTEDEV

Dai piccoli strumenti a uno sviluppo migliore.

support@tastedev.netSostieni TASTEDEV
ProdottiGamma di prodottiAcquistaDocsDownloadMarketplaceAssistenza
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrina
NormeChi siamoInformativa sulla privacyTermini di servizioCondizioni di abbonamentoRimborsiLinee guida della community
AccountAccediRegistrati
Visitatori
Oggi
Ieri
Visualizzazioni totali
Società
GXSOFT
Rappresentante
CHOI YOUNG GU
Numero di registrazione
853-44-00368
Indirizzo
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefono
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsabile privacy
CHOI YOUNG GU

© 2026 TASTEDEVLe informazioni sui prodotti si basano su fonti di sviluppo verificate.Rilasciato · in miglioramento

Documentazione di Django
Django
Getting Started with DjangoProject StructureCore ConceptsData and StateTestingDeployment
Discussioni

Guida a Django · 4/6

Data and State

Per ora questo capitolo è disponibile solo in inglese.

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)
Domande su questo capitolo?
Capitolo precedenteCore ConceptsCapitolo successivoTesting

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 commenti

Commenti principaliPrima i più recenti

Accedi · Accedi per lasciare un commento.