Django model模型, since 2022-01-14
2022-01-20 本文已影响0人
Mc杰夫
(2022.01.14 Fri)
placeholder
ORM
ORM, a.k.a., Object Relational Mapping,用于实现面向对象编程里面不同类型系统之间的数据转换。
生成model
(2022.01.20 Thur)
使用模型前,先创建一个专门的app,设置app的名字是db
,指令如下
$ pwd
/project_name
$ django-admin startapp db
此时会项目根目录下会出现新的文件夹db
,其中包含admin.py
, views.py
, models.py
等文件。
修改db/models.py
文件
from unittest.util import _MAX_LENGTH
from django.db import models
# Create your models here.
class ModelX(models.Model):
# primary_id = AutoField()
date_start = models.DateField()
date_end = models.DateField()
nation = models.CharField(max_length=30)
spot = models.CharField(max_length=30)
修改/project_name/project_name/settings.py
文件,加入db
app。
...
INSTALLED_APPS = [
...,
'db',
]
在根目录运行下列指令创建数据库
$ python manage.py makemigration db
$ python manage.py migrate db
在根目录下进入Django的shell环境,并手动输入新数据
$ python manage.py shell
...
In [1]: from db.models import ModelX
In [2]: ModelX.objects.create(date_start='2012-12-23', date_end='2012-12-27', nati
...: on='Spain', spot='Barcelona')
Out[2]: <ModelX: ModelX object (1)>
In [3]: ModelX.objects.get(spot='Barcelona')
Out[3]: <ModelX: ModelX object (1)>
In [4]: ModelX.objects.create(date_start='2021-11-04', date_end='2021-11-04', nati
...: on='China', spot='Suzhou')
Out[4]: <ModelX: ModelX object (2)>
通过下面指令查看数据表中的所有字段
In [5]: [term.name for term in ModelX._meta.fields]
Out[5]: ['id', 'date_start', 'date_end', 'nation', 'spot']
数据添加完成。之后修改根目录的urls.py
,添加如下代码
from db import urls
urlpatterns = [
...
path('db/', include(urls)),
]
在db
文件夹的urls.py
中添加如下
from django.contrib import admin
from django.urls import path, re_path, include
from . import views
urlpatterns = [
path('query-all/', views.query_all),
]
在db
文件夹的views.py
中添加方法
from django.shortcuts import render, redirect
from db.models import ModelX as mx
...
def query_all(requests):
db = mx.objects.all()
records_cntr = len(db)
fields_list = [term.name for term in mx._meta.fields]
res = []
for i in range(records_cntr):
ob = mx.objects.get(id=i+1)
ts = f"""response {i}: """
ts += f"""id={str(ob.id)}, date start={str(ob.date_start)},
date end={str(ob.date_end)}, nation={ob.nation}, spot={ob.spot}"""
res.append(ts)
return HttpResponse('\n'.join(res))
此时打开页面localhost:8000/db/query-all
即可返回数据结果。数据表达待调整。