INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'article',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'db55',
'USER':'root',
'PASSWORD':'root',
'HOST':'127.0.0.1',
'PORT':'3306',
}
}
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=100)
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
category = models.ForeignKey("Category",on_delete=models.CASCADE)
把模型映射到数据库当中,(具体参考47_Django数据库_创建和映射ORM模型)
from django.shortcuts import render
from .models import Category,Article
from django.http import HttpResponse
def index(request):
category = Category(name='财经频道')
category.save()
article = Article(title='abvc',content='sadligasdlkhgh')
article.category = category
article.save()
return HttpResponse("success")
from django.urls import path
from . import views
app_name = 'article'
urlpatterns = [
path('',views.index,name='index')
]
from django.urls import path,include
urlpatterns = [
path('', include('article.urls')),
]
8. 获取文章对应的category
更新views.py文件中的代码
from django.shortcuts import render
from .models import Category,Article
from django.http import HttpResponse
def index(request):
article = Article.objects.first()
print(article.category.name)
return HttpResponse("success")
9. 引用另一个app中的模型
新建一个app,名为frontuser
将frontuser添加到installed app中
在frontuser app的models.py中更新代码
from django.db import models
class Frontuser(models.Model):
username = models.CharField(max_length=200)
把模型映射到数据库当中,(具体参考47_Django数据库_创建和映射ORM模型)
在article app下面的models.py文件中更新代码
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=100)
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
category = models.ForeignKey("Category",on_delete=models.CASCADE)
author = models.ForeignKey("frontuser.Frontuser",on_delete=models.CASCADE)
通过makemigrations和migrate将数据库重新映射,数据库中article表格将增加author_id列,如下图所示:
10. 模型外键引用自己的模型
在article中的models.py文件中更新代码:
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=100)
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
category = models.ForeignKey("Category",on_delete=models.CASCADE)
author = models.ForeignKey("frontuser.Frontuser",on_delete=models.CASCADE,null=True)
class Comment(models.Model):
content = models.TextField()
origin_comment = models.ForeignKey("self",on_delete=models.CASCADE)
把模型映射到数据库当中,(具体参考47_Django数据库_创建和映射ORM模型)
来源:知了课堂