每个模型层都可以被映射为数据库中的一个数据库,而类属性被映射为数据字段,除此之外,数据表的主键、外键、约束等都可以通过属性完成定义
from django.db import models
class Category(models.Model):
name = models.CharField(verbose_name="分类名称",max_length=20)
create_time = models.DateTimeField(verbose_name="创建时间",auto_now_add=True)
update_time = models.DateTimeField(verbose_name="更新时间",auto_now=True)
def __str__(self):
return self.name
class Meta:
verbose_name = "分类表"
verbose_name_plural = verbose_name
class Article(models.Model):
title = models.CharField(verbose_name="文章标题",max_length=50)
desc = models.CharField(verbose_name="文章描述",max_length=100)
content = models.TextField(verbose_name="文章内容")
img = models.ImageField(verbose_name="文章图片",null=True,blank=True,upload_to='./static')
show_count = models.IntegerField(verbose_name="查看次数",default=0)
category = models.ForeignKey(Category,on_delete=models.PROTECT,verbose_name="分类")
create_time = models.DateTimeField(verbose_name="创建时间",auto_now_add=True)
update_time = models.DateTimeField(verbose_name="更新时间",auto_now=True)
def __str__(self):
return self.title
class Meta:
db_table = "article"
verbose_name = "文章"
verbose_name_plural = verbose_name
后通过 命令输入数据库
python manage.py makemigrations
python manage.py migrate
单独的python文件想要去查询数据库
import os,django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tqz_django.settings')
django.setup()
from user import models
需要去添加相关代码 如果需要在admin网站上看到这些数据,需要在admin.py添加该类
from django.contrib import admin
from . import models
admin.site.register(models.Category)
admin.site.register(models.Article)
在admin后台添加数据,可以在网页看到,写for循环并且显示数据
<div class="card border-0 rounded-0 px-3 mb-2 mb-md-3" id="category-card">
<div class="card-header bg-white px-0">
<strong><i class="fa fa-book mr-2 f-17"></i>文章分类</strong>
</div>
<ul class="list-group list-group-flush f-16">
{% for category in categories %}
<li class="list-group-item d-flex justify-content-between align-items-center pr-2 py-2">
<a class="category-item" href="/category?id={{ category.id }}" title="查看【CI/CD】分类下所有文章">{{ category.name }}</a>
<span class="badge text-center" title="当前分类下有6篇文章">{{ category.article_set.count }}</span>
</li>
{% endfor %}
</ul>
</div>
|