django models
Posted mingxiazhichan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django models相关的知识,希望对你有一定的参考价值。
python 中对数据库进行操作的模块为models。
1.创建一个数据库
models.py
from django.db import models # Create your models here. class Employee(models.Model): name=models.TextField(max_length=50) def __str__(self): return self.name
之后执行添加数据库命令:
python manage.py makemigrations python manage.py migrate
登录数据库验证.
2.查询/操作数据库
1.通过django shell
python manage.py shell 1.向数据库添加数据的三种方式 >>> from fir.models import Employee >>> emp=Employee() >>> emp.name=‘zhoujielun‘ >>> emp.save() >>> >>> emp2=Employee(name=‘lixiang‘) >>> emp2.save() >>> >>> emp3=Employee.objects.create(name=‘zhouxingxing‘)
>>> res=Employee.objects.all() >>> res <QuerySet [<Employee: zhoujielun>, <Employee: ligen>, <Employee: zouzou>, <Employee: zouzou>, <Employee: zhoujielun>, <Employee: lixiang>, <Employee: zhouxingxing>]> >>> for i in res: ... print(i) ... zhoujielun ligen zouzou zouzou zhoujielun lixiang zhouxingxing
通过视图函数查询/添加数据库
#views.py from fir.models import Employee def test(req): res=Employee.objects.all() return render(req,‘test.html‘,locals()) #urls.py from fir import views urlpatterns = [ path(r‘blog/test/‘,views.test) ] #test.html <html> <head> <title>test</title> </head> <body> {% for item in res %} {{forloop.counter}} {{item}} {% endfor %} </body> </html>
以上是关于django models的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Django Summernote 中显示编程片段的代码块?
django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE的解决办法(转)(代码片段