0Pricing
Flask Academy · Lekcja

Definiowanie relacji i kluczy obcych

Łącz modele relacjami jeden-do-wielu.

Definiowanie relacji i kluczy obcych to bezpłatna lekcja Flask Academy na CoddyKit. To lekcja 3 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Flask Academy, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Flask Academy zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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! 🎉

Często zadawane pytania

Czy lekcja „Definiowanie relacji i kluczy obcych” jest bezpłatna?

Tak — pełny tekst „Definiowanie relacji i kluczy obcych” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Flask Academy, przejdź na CoddyKit PRO. Kurs Flask Academy zawiera 4 lekcji w sumie.

Co nauczysz się w „Definiowanie relacji i kluczy obcych”?

Łącz modele relacjami jeden-do-wielu. Ćwiczysz Flask Academy z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Flask Academy?

Nie wymagamy żadnego doświadczenia. Flask Academy w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 4.

Ile czasu zajmuje lekcja „Definiowanie relacji i kluczy obcych”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Flask Academy?

Tak. Każda lekcja Flask Academy zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Pobieranie wierszy za pomocą query i get
  2. Filtrowanie, sortowanie i ograniczanie wyników
  3. Definiowanie relacji i kluczy obcych
  4. Złączenia oraz ładowanie leniwe i chętne
← Powrót do Flask Academy