晚上失眠,实在无事,翻了翻官方文档初识 Django | Django documentation | Django
好吧,所谓模型API实质就是数据库的一些操作接口(还是很不习惯叫数据为模型,模型应该是CNN、Deeplab、UNet、Yolo……)
# models
# #########################一个简单的数据模型就此诞生###############
from django.db import models
class Reporter(models.Model):
full_name = models.CharField(max_length=70) # 仅仅定义了一个字段
def __str__(self):
return self.full_name # 返回一个易于阅读的字符串表示,以便在 Django Admin 或其他地方显示时,能够更加直观地显示该对象的信息。
一些常规用法:
# Import the models we created from our "news" app
>>> from news.models import Article, Reporter
# No reporters are in the system yet.
>>> Reporter.objects.all()
<QuerySet []>
# .all 我一直认为是直接展示所有的数据库信息,刚才测试了下才发现,原来只是创建一个查询集类似的东西,和上面str有关,本质并没有访问数据库。只有实际print或者切片或者其他啥操作时候,才会真的去访问数据库。如果想看某一行数据或者全部可以这样:
a = Customer.objects.all()
for s in a:
print(vars(s))
# 或者单独把每个字段都打出来print(f"ID: {reporter.id}, Full Name: {reporter.full_name}")
# Create a new Reporter.
>>> r = Reporter(full_name="John Smith")
# Save the object into the database. You have to call save() explicitly.
>>> r.save()
# Now it has an ID.
>>> r.id
1
# Now the new reporter is in the database.
>>> Reporter.objects.all()
<QuerySet [<Reporter: John Smith>]>
# Fields are represented as attributes on the Python object.
>>> r.full_name
'John Smith'
# Django provides a rich database lookup API.
>>> Reporter.objects.get(id=1)
<Reporter: John Smith>
>>> Reporter.objects.get(full_name__startswith="John")
<Reporter: John Smith>
>>> Reporter.objects.get(full_name__contains="mith")
<Reporter: John Smith>
>>> Reporter.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Reporter matching query does not exist.
# 众所周知,在权限控制时候,我们还用到了filter,似乎和这儿get起到了类似的作用。具体区别在于:filter返回的是一个QuerySet对象(查询集),如果没有不会抛出异常;而get直接返回模型对象,而且只能返回一个,没有会报错。