Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

update the ForeignKey field for Django 2.0 #42

Open
wants to merge 3 commits into
base: 1.8
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion 07-django-models.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class Store(models.Model):

class MenuItem(models.Model):

store = models.ForeignKey('Store', related_name='menu_items')
store = models.ForeignKey('Store', related_name='menu_items', on_delete=models.SET_NULL, null=True)
name = models.CharField(max_length=20)
price = models.IntegerField()

Expand All @@ -45,6 +45,8 @@ class MenuItem(models.Model):

在 `ForeignKey` 的狀況中,Django 預設會用 model 的名稱後面加 `_set` 來當作 reverse relation 的名稱,所以 `MenuItem.store` 的預設 reverse relation key 會是 `Store.menuitem_set`。你當然可以直接使用這個值,不過如果狀況允許,我個人推薦盡量還是手動設定這個值。即使設成和預設一樣,也比沒有設定好,因為 *explicit is better than implicit* 是 Python 的中心思想之一。

`ForeignKey` 還有第三個 attribute `on_delete`,其值的選項可以參見[官方文件](https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.ForeignKey.on_delete)。

我們另外在兩個 models 都各加上了一個 [`__str__`](https://docs.python.org/3/reference/datamodel.html#object.__str__) 函式。這是 Python 用來把物件轉換成 `str` 的 hook;因為做網站時,常常需要把東西變成字串,所以這會很方便。

現在程式已經可以認得這兩種 models 了。但如果要儲存它們,還需要在資料庫裡建立對應的 tables。確保資料庫與程式中的定義同步,是件很麻煩的工作;幸好,Django 提供了一個自動同步資料表的工具,可以協助我們完成這個工作。
Expand Down