0Pricing
Flask Academy · Lezione

Definire relazioni e chiavi esterne

Colleghi i model con associazioni uno-a-molti.

Definire relazioni e chiavi esterne è una lezione Flask Academy gratuita su CoddyKit. Questa è la lezione 3 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Flask Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Flask Academy include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Rows That Belong Together

Real data connects: a user has many posts, an order has many items. A relationship links these rows in your models. 🔗

The Foreign Key

A foreign key is a column on the child that stores the parent's id. It is the actual link saved in the database.

user_id = db.Column(db.Integer, db.ForeignKey("user.id"))

Point at the Right Table

Inside ForeignKey you name the target as table.column, using the lowercase table name Flask-SQLAlchemy generates.

db.ForeignKey("user.id")

Add a relationship

The relationship() helper turns that key into easy navigation, so you reach linked objects as attributes.

posts = db.relationship("Post")

One-to-Many in Practice

Put the foreign key on the many side and the relationship on the one side. One user, many posts.

class Post(db.Model):
    user_id = db.Column(db.ForeignKey("user.id"))

Navigate Parent to Children

Once linked, read a parent's children like a list. SQLAlchemy fetches them for you on access. ✨

user = User.query.first()
for p in user.posts:
    print(p.title)

Walk Back with backref

Add backref to a relationship and the child instantly gains a way to reach its parent.

posts = db.relationship("Post", backref="author")

Use the Backref

That backref lets you go from a child straight back to its owner with a clean attribute. 🙌

post = Post.query.first()
print(post.author.name)

Assign by Object

Link rows by setting the relationship attribute to an object. SQLAlchemy fills in the foreign key for you.

post = Post(title="Hi")
post.author = user

Cascade on Delete

Set a cascade so deleting a parent can also remove its children, keeping the database tidy and consistent.

db.relationship("Post", cascade="all, delete")

Key vs Relationship

The foreign key stores the link in SQL; relationship is the Python convenience layer on top of it. You usually want both.

Quick Check

One user can write many posts. Where does the foreign key column live?

Recap: Linking Models

You now connect tables with a foreign key, navigate them via relationship and backref, and control deletes with cascade. Models, united! 🎉

Domande Frequenti

La lezione «Definire relazioni e chiavi esterne» è gratuita?

Sì — il testo completo di «Definire relazioni e chiavi esterne» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Flask Academy, passa a CoddyKit PRO. Il corso Flask Academy include 4 lezioni in totale.

Cosa imparerò in «Definire relazioni e chiavi esterne»?

Colleghi i model con associazioni uno-a-molti. Eserciti Flask Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Flask Academy?

Non è richiesta alcuna esperienza precedente. Flask Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 3 di 4.

Quanto tempo richiede la lezione «Definire relazioni e chiavi esterne»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Flask Academy?

Sì. Ogni lezione Flask Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Recuperare righe con query e get
  2. Filtrare, ordinare e limitare i risultati
  3. Definire relazioni e chiavi esterne
  4. Join e caricamento lazy o eager
← Torna a Flask Academy