# 注意:在定义一个模型的时候,模型的名字的首字母必定要大写,否者的话,模型名字下面会出现波浪线。 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)