zl程序教程

您现在的位置是:首页 >  后端

当前栏目

django ORM中update_or_create功能,如果只要匹配某一特定字段呢

django 功能 or 匹配 字段 create update 如果
2023-09-27 14:28:45 时间
今天发现的需求,在官方文档找到说法: In English, that means start with any non- defaults  keyword argument that doesn’t contain a double underscore (which would indicate a non-exact lookup).

今天发现的需求,在官方文档找到说法:

In English, that means start with any non-defaults keyword argument that doesn’t contain a double underscore (which would indicate a non-exact lookup). Then add the contents of defaults, overriding any keys if necessary, and use the result as the keyword arguments to the model class. As hinted at above, this is a simplification of the algorithm that is used, but it contains all the pertinent details. The internal implementation has some more error-checking than this and handles some extra edge-conditions; if you’re interested, read the code.

If you have a field named defaults and want to use it as an exact lookup in get_or_create(), just usedefaults__exact, like so:


Foo.objects.get_or_create(defaults__exact=bar, defaults={defaults: baz})


所以,用__exact指定即可,比如,我所面对的:

obj, created = Table.objects.update_or_create(

 dv__exact=dv_f, description=description)

 


Django ORM Model的基本查询操作API 1.创建Model实例对象 阅读文本前请参考此文章的数据表结构 使用save方法创建Model实例: 由于Topic需要一个User对象,所以,先获取username是admin(超级用户)的User对象,再去创建Topic对象
Django ORM 聚合查询和分组查询 对QuerySet计算统计值,需要使用aggregate方法,提供的参数可以是一个或多个聚合函数 Django提供了一系列的聚合函数,其中Avg(平均值)、Count(计数)、Max(最大值)、Min(最小值)、Sum(加和)最为常用 要使用这些聚合函数,需要将它们引入当前的环境中:
Django ORM F对象和Q对象查询 F对象用于操作数据库中某一列的值,它可以在没有实际访问数据库获取数据值的情况下对字段的值进行引用 使用F对象之前需要将它引入当前的环境中:
Django ORM基本应用与原理剖析 1.ORM构建数据表 由于每一个数据表对应一个Model定义,每一个Model都是一个Python类,所以,Model之间是可以继承的。Django规定,所有的Model都必须继承自django.db.models.Model
Django跟某几个字段去重MySQL Django官方文档提供了使用distinct进行去重的操作,但是只支持`PostgreSQL`,具体操作可以看官方文档,就不再过多赘述。这里写的是一种支持MySQL进行去重的操作。