#ForeignKey
Django: đặt related_name và on_delete đúng cách để quan hệ không còn rối

Khi một model trỏ tới model khác bằng ForeignKey, Django cần biết hai điều: gọi ngược từ bản ghi cha sang danh sách bản ghi con bằng tên nào, và khi bản ghi cha bị xóa thì bản ghi con sẽ ra sao. Đặt related_name rõ nghĩa và…
Django: đặt related_name và on_delete đúng cách để quan hệ không còn rối
Khi một model trỏ tới model khác bằng ForeignKey, Django cần biết hai điều: gọi ngược từ bản ghi cha sang danh sách bản ghi con bằng tên nào, và khi bản ghi cha bị xóa thì bản ghi con sẽ ra sao. Đặt related_name rõ nghĩa và chọn on_delete đúng giúp code dễ đọc và tránh xóa nhầm dữ liệu.
linhfish.dev
November 3, 2026 at 11:10 PM
Bài này vẫn còn nguyên giá trị cho ai đang tối ưu API Django REST Framework: Django REST Framework: loại bỏ N+1 query trong ViewSet bằng select_related và prefetch_related — chỉ còn 3 query cho mọi số lượng bài viết.
Django REST Framework: loại bỏ N+1 query trong ViewSet bằng select_related và prefetch_related
Mở đầu API Django REST Framework chạy chậm ở endpoint list thường do lỗi N+1 query: mỗi object trong danh sách lại gây thêm 1-2 truy vấn tới bảng liên quan. Giải pháp là override get_queryset() trong ViewSet và thêm select_related() cho quan hệ ForeignKey/OneToOne, prefetch_related() cho ManyToMany/quan hệ ngược. Áp dụng ngay khi serializer của bạn truy xuất field liên quan — hiệu quả thấy rõ trên mọi endpoint list.
linhfish.dev
November 3, 2026 at 1:11 PM
Django: sửa trang admin “đơ” khi ForeignKey có hàng nghìn bản ghi bằng autocomplete_fields trong 5 phút

Khi một model Django có ForeignKey trỏ tới bảng vài nghìn bản ghi, trang thêm/sửa trong admin render một thẻ select chứa toàn bộ dòng — trang tải chậm, thậm chí treo trình duyệt yếu. Giải pháp…
Django: sửa trang admin “đơ” khi ForeignKey có hàng nghìn bản ghi bằng autocomplete_fields trong 5 phút
Khi một model Django có ForeignKey trỏ tới bảng vài nghìn bản ghi, trang thêm/sửa trong admin render một thẻ select chứa toàn bộ dòng — trang tải chậm, thậm chí treo trình duyệt yếu. Giải pháp là autocomplete_fields: biến select thành ô tìm kiếm AJAX, chỉ tải bản ghi khi người dùng gõ chữ. Áp dụng cho mọi ForeignKey và ManyToManyField có nhiều bản ghi liên quan.
linhfish.dev
October 21, 2026 at 9:07 AM
Flask: định nghĩa relationship đúng cách trong Flask-SQLAlchemy — điều hướng hai chiều trong 5 phút

Hầu hết model Flask-SQLAlchemy đều có quan hệ với nhau — một User có nhiều Order, một Author viết nhiều Post. Nhiều người chỉ khai báo ForeignKey mà quên mất relationship(). Chỉ với hai dòng khai…
Flask: định nghĩa relationship đúng cách trong Flask-SQLAlchemy — điều hướng hai chiều trong 5 phút
Hầu hết model Flask-SQLAlchemy đều có quan hệ với nhau — một User có nhiều Order, một Author viết nhiều Post. Nhiều người chỉ khai báo ForeignKey mà quên mất relationship(). Chỉ với hai dòng khai báo db.relationship() cùng back_populates, bạn điều hướng đối tượng hai chiều: user.orders trả về danh sách đơn hàng, order.user trả về chủ đơn.
linhfish.dev
October 18, 2026 at 3:24 AM
Bài này vẫn còn nguyên giá trị cho anh em làm Django: lỗi N+1 query rất phổ biến, và cách sửa bằng select_related chỉ mất 5 phút. Đọc lại cho chắc nhé 👇

Django: sửa lỗi N+1 query bằng select_related trong 5 phút
Django: sửa lỗi N+1 query bằng select_related trong 5 phút
Lỗi N+1 query là khi bạn lấy một danh sách N bản ghi rồi truy cập trường quan hệ (ForeignKey) trên từng bản ghi, khiến Django phát sinh thêm N câu query — với 100 bài viết, trang của bạn sẽ chạy 101 câu query thay vì 1. Cách sửa trong Django rất đơn giản: thêm .select_related('ten_quan_he') vào queryset để Django JOIN bảng liên quan ngay từ query đầu tiên, gom toàn bộ thành đúng 1 câu query.
linhfish.dev
October 17, 2026 at 1:18 PM
Django Fellow Report- Sarah

Sarah Boyce triaged and reviewed Django fixes covering Playwright testing, admin query parameters, annotation transforms, and GEOS 3.15 compatibility. She also documented the YYYY[.N] release-versioning scheme and #djangonews

forum.djangoproject.com/t/django-fe...
Django Fellow Report - Sarah - 2026
Week ending 2026-09-13 (Week 37) This week was quite admin heavy but all positive things! Triaged #37306 (Add --tracing and --video options to the Playwright test runner) – Django (accepted) #37337 (MigrationAutodetector defers ForeignKey components of CompositePrimaryKey to AddField, causing FieldDoesNotExist on CreateModel) – Django (worksforme) #37330 (Transform on an annotation alias crashes when output_field is not attached to a model) – Django (accepted) #37341 (Update "vast range" phras...
forum.djangoproject.com
September 23, 2026 at 10:00 PM
Django 6.1 adds model field fetch modes that can reduce many N plus 1 query cases, database level ForeignKey delete options, and dictionary based email settings. It supports Python 3.12 through 3.14, so review upgrade notes first.
August 27, 2026 at 11:44 AM
Django 6.1 adds model field fetch modes that can reduce many N plus 1 query cases, database level ForeignKey delete options, and dictionary based email settings. It supports Python 3.12 through 3.14, so review upgrade notes first.
August 27, 2026 at 9:14 AM
Django のForeignKey まわりがよくわからない
May 18, 2025 at 10:24 PM
About Default ForeignKey Value
www.djangotricks.com/tricks/3KUVg...
About Default ForeignKey Value
www.djangotricks.com
December 5, 2025 at 6:39 PM
When you're coding in Django, you'll likely need to connect pieces of data. This is where ForeignKey comes in - it helps you link one model to another. John teaches you how it works, how to access related objects, how to create foreign key relationships, & more.
www.freecodecamp.org/news/how-to-...
April 23, 2025 at 12:01 AM
EF Core. In model class, what style do you use

#dotnet
EF Core. In model class, what style do you use
> >\[Required\] >\[ForeignKey("CategoryId")\] >\[Display(Name = "Category Type")\] >public int CategoryId { get; set;...
old.reddit.com
January 17, 2025 at 5:04 AM
Foreign key fields now let you control referential integrity policies directly from the model definition.

Previously, Cot always generated RESTRICT for both policies. Now you can choose any standard option giving you full control over what happens when a referenced row is updated or deleted.
July 13, 2026 at 6:40 PM
Connecting #Django admin inline object should be simpler for objects without direct foreignkey. Something like overriding a simple "get_queryset" 😒😒
April 10, 2025 at 5:43 PM
SQLAlchemy applications can connect to Aurora DSQL by using UUID primary keys, defining relationships with explicit `primaryjoin` and `foreign()` annotations instead of `ForeignKey()` constraints, and configuring the engine in AUTOCOMMIT mode to avoid unsupported SAVEPOINT operations.
Building Python applications with SQLAlchemy and Aurora DSQL
SQLAlchemy applications can connect to Aurora DSQL by using UUID primary keys, defining relationships with explicit `primaryjoin` and `foreign()` annotations instead of `ForeignKey()` constraints, and configuring the engine in AUTOCOMMIT mode to avoid unsupported SAVEPOINT operations.
aws-news.com
June 8, 2026 at 8:12 PM
Django 6.1 is out now!

New features include:

🐍Database level delete options for ForeignKey
🐍Dictionary based email settings
🐍Support for Python 3.12-3.14
🐍Model field fetch modes

and more!
August 7, 2026 at 12:56 PM
The "art of programming" might feel like it's crumbling, yet I'm still trying to keep up with software engineering developments. I'm now almost a year into learning event sourcing. It's satisfying to be able to write clean code even for legacy codebases. Sample con raffle feature—real world Python!
March 28, 2026 at 7:59 PM
Q: What sits between you and your Data? A: Identifiers! Read: #URI #LinkedData #PrimaryKey #ForeignKey #ODBC #NewSQL
November 21, 2024 at 8:03 AM
sqlalchemy、ForeignKeyの指定の仕方がよくわかってない。joinはわかった。
June 1, 2024 at 11:49 AM
Django 6.1 released

Django 6.1 is now available with features including model field fetch modes, database-level ForeignKey delete options, and dictionary-based email settings. Django 6.0 has ended mainstream support and will rec…

https://www.djangoproject.com/weblog/2026/aug/05/django-61-released/
August 13, 2026 at 6:15 AM
Project: django/django
File: tests/model_formsets/tests.py:1337

def test_unique_true_enforces_max_num_one(self): # ForeignKey with unique=True should enforce max_num=1

SVG: dark, light
August 30, 2025 at 10:36 PM
“Oh yeah the Flowery mmrs doesn’t work on recomp right now because I used stoi instead of stoll and one of the zsounds has DEADBEEF as its foreignKey”

Statements dreamt up by the utterly Deranged
July 6, 2026 at 6:10 PM
15five-django-ajax-selects - 1.5.2.155

Edit ForeignKey, ManyToManyField and CharField in Django Admin using jQuery UI AutoComplete.

Author: Chris Sattinger
August 6, 2024 at 10:00 PM
There’s a ticket for the ForeignKey migration issue he discusses: code.djangoproject.com/ticket/34417

The PR is half-written with review comments to address, if anyone would like to revive the code and finish it off!
#34417 (AlterField migration on ForeignKey field re-creates foreign key constraints unnecessarily) – Django
code.djangoproject.com
October 12, 2025 at 9:48 PM