# 注意:在定義一個模型的時候,模型的名字的首字母必定要大寫,否者的話,模型名字下面會出現波浪線。 class User(models.Model): username = models.CharField(max_length=20) password = models.CharField(max_length=100) class Article(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey('User',on_delete=models.CASCADE)
from django.http import HttpResponse from .models import User,Article def index(request): # 向數據庫表中添加一條數據,首先要先將被引用的表添加數據,並進行保存 user = User(username='孤煙逐雲', password='hello') user.save() article = Article(title='Python', content='真好') article.author = user article.save() return HttpResponse("Success ! ")
由於在底層,Django爲Article表添加了一個屬性名_id的字段(好比author的字段名稱是author_id),這個字段是一個外鍵,記錄着對應的做者的主鍵。之後經過article.author訪問的時候,其實是經過author_id找到對應的數據,而後再提取user表中的這條數據,造成一個模型。python
from django.http import HttpResponse from .models import User,Article def index(request): article = Article.objects.all() print(article) return HttpResponse("Success ! ")
class Article(models.Model): title = models.CharField(max_length=100) content = models.TextField() author = models.ForeignKey('User',on_delete=models.CASCADE) def __str__(self): return "<(Article id: %s, title: %s, content: %s, author: %s)>" % (self.id, self.title, self.content, self.author)
# Book模型在book,app中, from django.db import models class Book(models.Model): # 定義屬性,出版社的地址 pub_add = models.CharField(max_length=100) # 在article模型中進行外鍵引用 class Article(models.Model): title = models.CharField(max_length=100) content = models.TextField() # 使用外鍵引用同一個app下的模型 author = models.ForeignKey('User',on_delete=models.CASCADE) # 使用外鍵引用不一樣app下的模型 pub = models.ForeignKey('book.Book',on_delete=models.CASCADE)
orm_relationship _demo
.#sql-158c_79
, CONSTRAINT article_article_pub_id_e2e65cb7_fk_book_book_id
FOREIGN KEY (pub_id
) REFERENCES book _book
(id
))')# 取消對外鍵的檢查 'OPTIONS':{ "init_command":"SET foreign_key_checks = 0;", }
class Comment(models.Model): content = models.TextField() origion_comment = models.ForeignKey('self',on_delete=models.CASCADE)