In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article shows you how to understand the django template and single table ORM addition, deletion, modification and query, the content is concise and easy to understand, absolutely can make your eyes bright, through the detailed introduction of this article, I hope you can get something.
1.Django template syntax: variables: {{}} 1 Deep query period character 2 filter {{val | filter_name: parameter}} tag: {%} 1.1Django template uses from django.shortcuts import renderimport datetimedef index (request): now = datetime.datetime.now () return render (request, "index.html", {"current_time": now}) 1.2 template syntax variables
Views.py
From django.shortcuts import renderimport datetimedef index (request): my_string = "hello" my_list = [111,222 "," www "] my_dict = {" name ":" vita "," age ": 23} my_date = datetime.date (1992, 1,19) my_bool = True class Person (object): def _ init__ (self) Name): self.name = name @ staticmethod def func (): return "my func" person1 = Person ("vita") person2 = Person ("lili") person_list = [person1, person2] # method 1: # return render (request, "index.html", {"my_string": my_string, "my_list": my_list, "my_dict": my_dict "my_date": my_date, "my_bool": my_bool, "person_list": person_list}) # method 2: # locals () mainly returns local variables to the page The variable name is the same return render as the variable name in the function (request, "index.html", locals ())
Index.html
Title h5 {color:blue;} h6 {color: yellowgreen } string my_string: {{my_string}} list my_list: {{my_list}} my_list.0: {{my_list.0}} my_list.1: {{my_list.1}} dictionary my_dict: {{my_dict}} my_dict.name: {{my_dict.name}} my_dict.age: {{my_dict.age}} date my_date: {{my_date}} my_date.year: {{my_date.year}} Boolean my_bool: {{my_bool}} Class object list person_list: {{person_list}} person_list.0.name: {{person_list.0.name}} person_list.0.func: {{person_list.0.func}}
1.3The template filter 1.3.1 Syntax {{obj | filter__name:param}} 1.3.2 comes with a filter 1.default {{value | default: "nothing"}} if a variable is false or empty, use the given default value. Otherwise, use the value of the variable. 2.length {{value | length}} the length of the value returned. Works for both strings and lists. If value is [1, 2, 3, 3, 4, 4], then the output value is 5. 3.date if value=datetime.datetime.now () {{value | date: "Y-m-d"} 4.slice if value= "hello world" {{value | slice: "2value 1"}} 5.truncatechars {{value | truncatechars:9}} Parameter: the number of characters to be truncated, that is, the number of characters retained if the string characters are more than the specified number of characters, then it will be truncated. The truncated string will be translated with an ellipsis (".") The end of the sequence. 6.truncatewords {{my_word | truncatewords:3}} parameter: 7.safest = "Click" {{value | safe}} tell Django that this code is safe and does not need to be escaped. 8.filesizeformat {{file_size | filesizeformat}} converts digits into from django.shortcuts import renderimport datetimedef index (request) such as KB,M,G: my_string = "hello" my_list = [1,2,3,'a'] my_date = datetime.datetime.now () value = "Click" file_size = 12343242123123 my_word = "aa bb cc dd ee" return render (request, "index.html", locals ())
The tag {% tag%} 1.4.1for tag of the template traverses each element, and you can use {% for obj in list reversed%} to complete the reverse loop. Traversal dictionary {% for key,val in dic.items%}
{{key}}: {{val}}
{% endfor%} Note: the loop serial number can display forloop.counter The current iteration of the loop (1-indexed) forloop.counter0 The current iteration of the loop (0-indexed) forloop.revcounter The number of iterations from the end of the loop (1-indexed) forloop.revcounter0 The number of iterations from the end of the loop (0-indexed) forloop.first True if this is the first time through {{forloop}}. The through the loopforloop.last True if this is the last time through the loop1.4.2for...emptyfor tag has an optional {% empty%} clause So that you can take action when the given group is empty or not found. {% for person in person_list%}
{{person.name}}
{% empty%}
Sorry,no person here
The {% endfor%} 1.4.3if tag {% if%} evaluates a variable, and if its value is "True" (exists, is not empty, and is not a false of type boolean), the corresponding content block will output {% if num > 100or num.
< 0 %} 无效 {% elif num >80 and num
< 100 %} 优秀 {% else %} 凑活吧 {% endif %}1.4.4with使用一个简单的名字缓存一个很复杂的变量{% with total=business.employees.count %} {{ total }} employee{{ total|pluralize }}{% endwith %}1.4.5{%csrf_token%}用于跨站请求伪造保护。当请求为post请求时,由于在settings.py中配置了'django.middleware.csrf.CsrfViewMiddleware',如果不加这个标签,会报错。加上这个标签,就可以成功提交请求。原理:在第一次请求时,在html页面中生成一个隐藏的input标签。当提交请求时,django会验证,发现了这个标签,才能提交请求,否则提交失败。防止用户第一次就提交post请求。 1.4.6验证上面内容 views.py from django.shortcuts import renderimport datetimedef index(request): my_list = ["a", "b", "c"] my_dict = {"name": "vita", "age": 23} empty_list = [] class Person(object): def __init__(self, name): self.name = name person1 = Person("vita") person2 = Person("lili") person_list = [person1, person2] return render(request, "index.html", locals()) index.html Title循环列表 {% for item in my_list %} {{ item }} {% endfor %} {% for item in my_list %} {{ forloop.counter }}---{{ item }} {% endfor %} {% for item in my_list %} {{ forloop.counter0 }}---{{ item }} {% endfor %}反向完成循环 {% for item in my_list reversed %} {{ item }} {% endfor %} {% for item in my_list reversed %} {{ forloop.revcounter }}---{{ item }} {% endfor %} {% for item in my_list reversed%} {{ forloop.revcounter0 }}---{{ item }} {% endfor %}循环字典 {% for key,val in my_dict.items %} {{ key }}---{{ val }} {% endfor %}if循环 {% for item in my_list %} {% if forloop.first %} forloop.first--{{ item }} {% elif forloop.last %} forloop.last---{{ item }} {% else %} {{ item }} {% endif %} {% endfor %}empty {% for item in empty_list %} {{ item }} {% empty %} this is an empty list! {% endfor %}with别名 {% with person_list.0.name as p_name %} {{ p_name }} {% endwith %} csrf_token {% csrf_token %} 用户名: 密码:1.5 Custom tags and filters 1.5.1 introduction to Custom tags and filters 1. Configure the current app in INSTALLED_APPS in settings, otherwise Django will not be able to find the custom simple_tag. two。 Create a templatetags module in app (the module name can only be templatetags). 3. Create any .py file, such as my_tags.py. From django import template# can only be register, can not be another name register=template.Library () @ register.filterdef multi_fliter (XMague y): return x*y@register.simple_tagdef multi_tag (XMagol y): return x*y4. Import my_tags.py {% load my_tags%} 5 in html. Use filter and label {{num | filter_multi:2}} {% if num | filter_multi:2
< 50 %} {{ num|filter_multi:2 }} {% endif %} {% simple_tag_multi num 2 3 %}自定义的filter和simple_tag的区别1.filter最多只能传两个参数,可以用于if判断,使用{{}}。2.simple_tag可以传多个参数,不能用于if判断,使用{%%}。1.5.2小案例 views.py from django.shortcuts import renderimport datetimedef index(request): num = 12 return render(request, "index.html", locals()) index.html Title {% load my_tags %} {{ num|filter_multi:2 }} {% if num|filter_multi:2 < 50 %} {{ num|filter_multi:2 }} {% endif %} {% simple_tag_multi num 2 3 %} 1.6模板(include和extend)1.6.1介绍include:是把另一个html中的内容包含进当前html中extend:继承父html中的内容。注意:1.在模板中使用{%extend%}标签时,必须是模板中的第一个标签。否则模板继承无法工作2.在base模板中设置越多的{%block%}越好。 子模板不需要定义全部父模板中的blocks,所以,可以在大多数的blocks中填充合理的默认内容,然后,只定义你需要的一个。3.如果你发现自己在大量的模板中复制内容,可能意味着需要把该内容移动到父模板中的一个{%block%}中。4.为了更好的可读性,可以给{%endblock%}标签一个名字。{% block content %}...{% endblock content %}5.不能再一个模板中定义多个相同名字的block标签。6.可以使用{{block.super}}继承父block中的内容。7.可以覆盖父html中的所有block,也可以只重写某一个,没有被重写的使用的是父模板中的内容。1.6.2小案例 head.html head base.html {% block title %} title {% endblock %} *{ padding: 0; margin: 0; } .head{ background-color: yellowgreen; text-align: center; font-size: 20px; } .content{ background-color: pink; text-align: center; } .footer{ background-color: antiquewhite; text-align: center; } {% include "head.html" %} {% block content %} content father {% endblock content%} {% block footer %} footer father {% endblock footer%} index.html {% extends "base.html" %}{% block content %} {{ block.super }} child content {% endblock %}{% block footer %} child footer {% endblock %} 2.单表ORM增删改查2.1ORM简介MVC或MTV框架中包含的重要部分,就是ORM。它实现了数据模型与数据库的解耦,即数据模型的设计不需要依赖于特定的数据库,通过简单的配置就可以轻松的更换数据库。这极大地减轻了开发人员的工作,不需要面对数据库变更而导致的无效劳动。ORM即 "对象-关系-映射"。 2.2单表操作-创建表结构2.2.1创建models.pyfrom django.db import models# Create your models here.class Book(models.Model): id=models.AutoField(primary_key=True) title=models.CharField(max_length=32) state=models.BooleanField() pub_date=models.DateField() price=models.DecimalField(max_digits=8,decimal_places=2)#一共八位,小数位是2位 publish=models.CharField(max_length=32)#调用对象时,返回title def __str__(self): return self.title2.2.2常见的字段和参数1.CharField 字符串字段,用于较短的字符串。 CharFiled要求必须有一个参数maxlength,用于从数据库层和Django校验层限制该字段所允许的最大字符数。2.IntegerField 用于保存整数3.FloatField 一个浮点数,必须提供两个参数 参数一:max_digits 总位数(不包含小数点和符号) 参数二:decimal_places 小数位数 举例来说,要保存最大值为999(小数位保存2位),可以这样定义字段: models.FloatField(..., max_digits=5, decimal_places=2) 要保存最大值一百万(小数点后保存10位)的话,你要这样定义: models.FloatField(..., max_digits=19, decimal_places=10) admin 用一个文本框()表示该字段保存的数据.4.AutoField 一个整数字段,添加记录会自动增长。通常不需要直接使用这个字段。 定义一个主键:my_id=models.AutoField(primary_key=True) 如果不指定主键,系统会自动添加一个主键字段到你的model。5.BooleanField 一个true/false字段。admin用checkbox表示此类字段。6.TextField 一个容量很大的文本字段 admin用一个表示该字段的数据,一个多行编辑框。7.EmailField 一个带有检查Email合法性的CharField,不接受maxlength参数。8.DateField 一个日期字段,共有下面额外可选参数 Argument:描述 auto_now:当对象被保存时,自动将该字段的值设置为当前时间。通常用于表示"last-modified"时间戳。 auto_now_add 当对象首次被创建时,自动将该字段的值设置为当前时间。通常用于表示对象创建时间。9.DateTimeField 一个日期时间字段。类似DateField支持同样的附加选项。10.ImageField 类似FileField,不过要校验上传对象是否是一个合法图片。 他有两个可选参数:height_field和width_field,如果提供这两个参数,则图片将按照提供的高度和宽度保存。 FileField 一个文件上传字段. 要求一个必须有的参数: upload_to, 一个用于保存上载文件的本地文件系统路径. 这个路径必须包含 strftime #formatting, 该格式将被上载文件的 date/time 替换(so that uploaded files don't fill up the given directory). admin 用一个部件表示该字段保存的数据(一个文件上传部件) . 注意:在一个 model 中使用 FileField 或 ImageField 需要以下步骤: (1)在你的 settings 文件中, 定义一个完整路径给 MEDIA_ROOT 以便让 Django在此处保存上传文件. (出于性能考虑,这些文件并不保存到数据库.) 定义MEDIA_URL 作为该目录的公共 URL. 要确保该目录对 WEB服务器用户帐号是可写的. (2) 在你的 model 中添加 FileField 或 ImageField, 并确保定义了 upload_to 选项,以告诉 Django 使用 MEDIA_ROOT 的哪个子目录保存上传文件.你的数据库中要保存的只是文件的路径(相对于 MEDIA_ROOT). 出于习惯你一定很想使用 Django 提供的 get__url 函数.举例来说,如果你的 ImageField 叫作 mug_shot, 你就可以在模板中以 {{ object.#get_mug_shot_url }} 这样的方式得到图像的绝对路径. URLField 用于保存 URL. 若 verify_exists 参数为 True (默认), 给定的 URL 会预先检查是否存在( 即URL是否被有效装入且 没有返回404响应). admin 用一个 文本框表示该字段保存的数据(一个单行编辑框) NullBooleanField 类似 BooleanField, 不过允许 NULL 作为其中一个选项. 推荐使用这个字段而不要用 BooleanField 加 null=True 选项 admin 用一个选择框 (三个可选择的值: "Unknown", "Yes" 和 "No" ) 来表示这种字段数据. SlugField "Slug" 是一个报纸术语. slug 是某个东西的小小标记(短签), 只包含字母,数字,下划线和连字符.#它们通常用于URLs 若你使用 Django 开发版本,你可以指定 maxlength. 若 maxlength 未指定, Django 会使用默认长度: 50. #在 以前的 Django 版本,没有任何办法改变50 这个长度. 这暗示了 db_index=True. 它接受一个额外的参数: prepopulate_from, which is a list of fields from which to auto-#populate the slug, via JavaScript,in the object's admin form: models.SlugField (prepopulate_from=("pre_name", "name"))prepopulate_from 不接受 DateTimeFields. XMLField 一个校验值是否为合法XML的 TextField,必须提供参数: schema_path, 它是一个用来校验文本的 RelaxNG schema #的文件系统路径. FilePathField 可选项目为某个特定目录下的文件名. 支持三个特殊的参数, 其中第一个是必须提供的. 参数 描述 path 必需参数. 一个目录的绝对文件系统路径. FilePathField 据此得到可选项目. Example: "/home/images". match 可选参数. 一个正则表达式, 作为一个字符串, FilePathField 将使用它过滤文件名. 注意这个正则表达式只会应用到 base filename 而不是 路径全名. Example: "foo.*\.txt^", 将匹配文件 foo23.txt 却不匹配 bar.txt 或 foo23.gif. recursive可选参数.要么 True 要么 False. 默认值是 False. 是否包括 path 下面的全部子目录. 这三个参数可以同时使用. match 仅应用于 base filename, 而不是路径全名. 那么,这个例子: FilePathField(path="/home/images", match="foo.*", recursive=True) ...会匹配 /home/images/foo.gif 而不匹配 /home/images/foo/bar.gif IPAddressField 一个字符串形式的 IP 地址, (i.e. "24.124.1.30"). CommaSeparatedIntegerField 用于存放逗号分隔的整数值. 类似 CharField, 必须要有maxlength参数.2.2.3更多参数(1)null如果为True,Django 将用NULL 来在数据库中存储空值。 默认值是 False.(1)blank如果为True,该字段允许不填。默认为False。要注意,这与 null 不同。null纯粹是数据库范畴的,而 blank 是数据验证范畴的。如果一个字段的blank=True,表单的验证将允许该字段是空值。如果字段的blank=False,该字段就是必填的。(2)default字段的默认值。可以是一个值或者可调用对象。如果可调用 ,每有新对象被创建它都会被调用。(3)primary_key如果为True,那么这个字段就是模型的主键。如果你没有指定任何一个字段的primary_key=True,Django 就会自动添加一个IntegerField字段做为主键,所以除非你想覆盖默认的主键行为,否则没必要设置任何一个字段的primary_key=True。(4)unique如果该值设置为 True, 这个数据字段的值在整张表中必须是唯一的(5)choices由二元组组成的一个可迭代对象(例如,列表或元组),用来给字段提供选择项。 如果设置了choices ,默认的表单将是一个选择框而不是标准的文本框, 而且这个选择框的选项就是choices 中的选项。2.2.4settings配置若想将模型转为mysql数据库中的表,需要在settings中配置:DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'bms', # 要连接的数据库,连接前需要创建好 'USER':'root', # 连接数据库的用户名 'PASSWORD':'', # 连接数据库的密码 'HOST':'127.0.0.1', # 连接主机,默认本级 'PORT':3306 # 端口 默认3306 }}2.2.5INSTALL_APPS中写入我们创建的app名称INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "app1"]2.2.6在项目名文件下的init中,导入驱动PyMySQLimport pymysqlpymysql.install_as_MySQLdb() 2.2.7如果想打印ORM转换过程中的sql,需要在settings.py中配置LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'propagate': True, 'level':'DEBUG', }, }}2.2.8建表python manage.py makemigrationspython manage.py migrate如果报错:django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.NoneMySQLclient目前只支持到python3.4,因此如果使用的更高版本的python,需要修改如下:通过查找路径C:\Programs\Python\Python36-32\Lib\site-packages\Django-2.0-py3.6.egg\django\db\backends\mysql \base.py这个路径里的文件把下面内容注释掉if version < (1, 3, 13): raise ImproperlyConfigured("mysqlclient 1.3.13 or newer is required; you have %s" % Database.__version__)我这里使用的Django2.2.2,Python3.6.2,使用sqllite不会出现上面的问题。使用mysql会报上面的问题。 2.2.9查看表我这里直接使用了默认的db.sqlite3 2.3ORM单表增删改查2.3.1添加表记录方式一:book_obj = Book.objects.create(title="python",state=True,price=100,publish="python_publish",pub_date="2012-12-12")方式二:book_obj2 = Book(title="java",state=True,price=100,publish="java_publish",pub_date="2012-12-12")book_obj2.save()返回值是一个book对象。 2.3.2查询表记录2.3.2.1all()查询所有结果all(): 查询所有结果返回值: queryset对象 这里由于在models.py中定义了__str__,所以返回值显示的是title。SQL语句: SELECT "app1_book"."id", "app1_book"."title", "app1_book"."state", "app1_book"."pub_date", "app1_book"."price", "app1_book"."publish" FROM "app1_book" LIMIT 21;from django.shortcuts import renderfrom app1.models import Bookdef index(request): # book_obj = Book.objects.create(title="python",state=True,price=100,publish="python_publish",pub_date="2012-12-12") book_list = Book.objects.all() print(book_list) # for obj in book_list: print(obj.title,obj.price) print(book_list[1].title,book_list[1].price) return render(request, "index.html") 2.3.2.2first(),last()first():返回第一条记录。last():返回最后一条记录。返回值: model对象,python 调用者: queryset对象SQL语句: first()----SELECT "app1_book"."id", "app1_book"."title", "app1_book"."state", "app1_book"."pub_date", "app1_book"."price", "app1_book"."publish" FROM "app1_book" ORDER BY "app1_book"."id" ASC LIMIT 1; last()----SELECT "app1_book"."id", "app1_book"."title", "app1_book"."state", "app1_book"."pub_date", "app1_book"."price", "app1_book"."publish" FROM "app1_book" ORDER BY "app1_book"."id" DESC LIMIT 1; 2.3.2.3filter()filter(): 它包含了与所给筛选条件相匹配的对象。返回值: queryset对象,SQL语句: SELECT "app1_book"."id", "app1_book"."title", "app1_book"."state", "app1_book"."pub_date", "app1_book"."price", "app1_book"."publish" FROM "app1_book" WHERE ("app1_book"."price" = '100' AND "app1_book"."title" = 'python') LIMIT 21;from django.shortcuts import renderfrom app1.models import Bookdef index(request): # book_obj = Book.objects.create(title="python",state=True,price=100,publish="python_publish",pub_date="2012-12-12") book_list = Book.objects.filter(price=100,title="python") print(book_list) print(Book.objects.filter(price=100,title="python").first()) return render(request, "index.html") 2.3.2.4get()get(): 有且只有一个查询结果时才有意义返回值: model对象,python SQL语句: SELECT "app1_book"."id", "app1_book"."title", "app1_book"."state", "app1_book"."pub_date", "app1_book"."price", "app1_book"."publish" FROM "app1_book" WHERE ("app1_book"."price" = '100' AND "app1_book"."title" = 'python');from django.shortcuts import renderfrom app1.models import Bookdef index(request): # book_obj = Book.objects.create(title="python",state=True,price=100,publish="python_publish",pub_date="2012-12-12") book_list = Book.objects.get(price=100,title="python") print(book_list,type(book_list)) print(book_list.price) return render(request, "index.html") 2.3.2.5exclude()exclude(): 排除某些数据返回值: queryset对象,SQL语句: SELECT "app1_book"."id", "app1_book"."title", "app1_book"."state", "app1_book"."pub_date", "app1_book"."price", "app1_book"."publish" FROM "app1_book" WHERE NOT ("app1_book"."title" = 'python') LIMIT 21;from django.shortcuts import renderfrom app1.models import Bookdef index(request): # book_obj = Book.objects.create(title="python",state=True,price=100,publish="python_publish",pub_date="2012-12-12") book_list = Book.objects.exclude(title="python") print(book_list)# return render(request, "index.html") 2.3.2.6order_by()order_by(): 排序。 可以按照多个列排序,即第一个列值相同,按照第二个列排序。 为负值,表示降序排序,正直表示升序排序。调用者: queryset对象返回值: queryset对象,SQL语句: SELECT "app1_book"."id", "app1_book"."title", "app1_book"."state", "app1_book"."pub_date", "app1_book"."price", "app1_book"."publish" FROM "app1_book" WHERE "app1_book"."price" = '100' ORDER BY "app1_book"."id" DESC, "app1_book"."price" ASC LIMIT 21;from django.shortcuts import renderfrom app1.models import Bookdef index(request): # book_obj = Book.objects.create(title="python",state=True,price=100,publish="python_publish",pub_date="2012-12-12") book_list = Book.objects.filter(price=100).order_by("-id", "price") print(book_list)# return render(request, "index.html") 2.3.2.7count()count(): 返回数据库中匹配查询(QuerySet)的对象数量。调用者: queryset对象返回值: int值SQL语句: SELECT COUNT(*) AS "__count" FROM "app1_book" WHERE "app1_book"."price" = '100';from django.shortcuts import renderfrom app1.models import Bookdef index(request): # book_obj = Book.objects.create(title="python",state=True,price=100,publish="python_publish",pub_date="2012-12-12") book_list = Book.objects.filter(price=100).count() print(book_list) return render(request, "index.html") 2.3.2.8exists()exist(): 如果QuerySet包含数据,就返回True,否则返回False调用者: queryset对象返回值: True或Falsefrom django.shortcuts import renderfrom app1.models import Bookdef index(request): # book_obj = Book.objects.create(title="python",state=True,price=100,publish="python_publish",pub_date="2012-12-12") book_list = Book.objects.filter(price=100).exists() print(book_list) return render(request, "index.html") 2.3.2.9values()与values_list()values()与values_list(): 返回相应的字段与对应的值。调用者: queryset对象返回值: queryset对象,values返回的是queryset的字典,values_list返回的是queryset的元组。 values(): values_list():SQL语句: values():SELECT "app1_book"."title", "app1_book"."price" FROM "app1_book" WHERE "app1_book"."price" = '100' LIMIT 21; values_list():SELECT "app1_book"."title", "app1_book"."price" FROM "app1_book" WHERE "app1_book"."price" = '100' LIMIT 21;from django.shortcuts import renderfrom app1.models import Bookdef index(request): # book_obj = Book.objects.create(title="python",state=True,price=100,publish="python_publish",pub_date="2012-12-12") book_values = Book.objects.filter(price=100).values("title","price") print(book_values) book_value_list = Book.objects.filter(price=100).values_list("title","price") print(book_value_list) return render(request, "index.html") 2.3.2.10distinct()distinct(): 从返回结果中剔除重复纪录调用者: queryset对象返回值: queryset对象,SQL语句: SELECT DISTINCT "app1_book"."price" FROM "app1_book" WHERE "app1_book"."price" = '100' LIMIT 21;from django.shortcuts import renderfrom app1.models import Bookdef index(request): # book_obj = Book.objects.create(title="python",state=True,price=100,publish="python_publish",pub_date="2012-12-12") book_values = Book.objects.filter(price=100).values("price").distinct() print(book_values) return render(request, "index.html") 2.3.2.11reverse()reverse(): 反转调用者: queryset对象返回值: queryset对象SQL语句: SELECT "app1_book"."title", "app1_book"."price" FROM "app1_book" WHERE "app1_book"."price" = '100' LIMIT 21;from django.shortcuts import renderfrom app1.models import Bookdef index(request): # book_obj = Book.objects.create(title="python",state=True,price=100,publish="python_publish",pub_date="2012-12-12") book_values = Book.objects.filter(price=100).values("title","price").reverse() print(book_values) return render(request, "index.html") 2.3.3模糊查询Book.objects.filter(price__in=[100,200,300]) SQL语句:SELECT "app1_book"."price", "app1_book"."title" FROM "app1_book" WHERE "app1_book"."price" IN ('100', '200', '300') LIMIT 21;Book.objects.filter(price__gt=100) SQL语句:SELECT "app1_book"."price", "app1_book"."title" FROM "app1_book" WHERE "app1_book"."price" >'100' LIMIT 21 FROM Book.objects.filter (price__lt=100) SQL statement: SELECT "app1_book". "price", "app1_book". "title" FROM "app1_book" WHERE "app1_book". "price" < '100' LIMIT 21 Book.objects.filter (price__range= [100200]) SQL statement: SELECT "app1_book". "price", "app1_book". "title" FROM "app1_book" WHERE "app1_book". "price" BETWEEN '100' AND' 200' LIMIT 21 Book.objects.filter (title__contains= "python") SQL statement: SELECT "app1_book". "price", "app1_book". "title" FROM "app1_book" WHERE "app1_book". "title" LIKE'% python%' LIMIT 21 Book.objects.filter (title__icontains= "Python") # is not case-sensitive SQL statements: SELECT "app1_book". "price", "app1_book". "title" FROM "app1_book" WHERE "app1_book". "title" LIKE'% Python%' LIMIT 21 Book.objects.filter (title__startswith= "py") SQL statement: SELECT "app1_book". "price", "app1_book". "title" FROM "app1_book" WHERE "app1_book". "title" LIKE 'py%' LIMIT 21 Book.objects.filter (pub_date__year=2012) SQL statement: SELECT "app1_book". "price", "app1_book". "title" FROM "app1_book" WHERE django_date_extract ('month', "app1_book". "pub_date") = 12 LIMIT 21
2.3.4 delete table record delete (): delete the corresponding data caller: queryset object or model object return value: (2, {'app1.Book': 2}) SQL statement: DELETE FROM "app1_book" WHERE "app1_book". "price" =' 100' From django.shortcuts import renderfrom app1.models import Bookdef index (request): # book_obj = Book.objects.create (title= "python", state=True,price=100,publish= "python_publish", pub_date= "2012-12-12") ret=Book.objects.filter (price=100). Delete () print (ret) Book.objects.filter (price=100). First (). Delete () return render (request, "index.html")
2.3.5 update table record update (): update table data caller: queryset object return value: number of rows updated SQL statement: UPDATE "app1_book" SET "title" = 'php' WHERE "app1_book". "price" =' 100' From django.shortcuts import renderfrom app1.models import Bookdef index (request): # book_obj = Book.objects.create (title= "python", state=True,price=100,publish= "python_publish", pub_date= "2012-12-12") ret=Book.objects.filter (price=100) .update (title= "php") print (ret) return render (request, "index.html")
The above content is how to understand the django template and the addition, deletion, modification and query of the single form ORM. Have you learned the knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.