首页>>后端>>Python->哪个版本的Django中objects(2023年最新分享)

哪个版本的Django中objects(2023年最新分享)

时间:2023-12-07 本站 点击:0

导读:本篇文章首席CTO笔记来给大家介绍有关哪个版本的Django中objects的相关内容,希望对大家有所帮助,一起来看看吧。

python的django内Grades.objects.get(gname="www")如何写包含"www"的呢?

使用__contains

Grades.objects.get(gname__contains="www")

网页链接

注意get必须取得且正好取得一条记录。如果Grades中有多条gname字段包含www的记录将抛出MultipleObjectsReturned异常,而如果没有记录符合条件将抛出DoesNotExist异常。

django2.1可以安装哪个版本drf

3.10.0版。

如果django安装的是2.0版本,建议安装以下版本,pip install djangorestframework==3.10.0。

django 2.0外键处理

Django2.0里model外键和一对一的on_delete参数

在django2.0后,定义外键和一对一关系的时候需要加on_delete选项,此参数为了避免两个表里的数据不一致问题,不然会报错:

TypeError: __init__() missing 1 required positional argument: 'on_delete'

举例说明:

user=models.OneToOneField(User)

owner=models.ForeignKey(UserProfile)

需要改成:

user=models.OneToOneField(User,on_delete=models.CASCADE)          --在老版本这个参数(models.CASCADE)是默认值

owner=models.ForeignKey(UserProfile,on_delete=models.CASCADE)    --在老版本这个参数(models.CASCADE)是默认值

参数说明:

on_delete有CASCADE、PROTECT、SET_NULL、SET_DEFAULT、SET()五个可选择的值

CASCADE:此值设置,是级联删除。

PROTECT:此值设置,是会报完整性错误。

SET_NULL:此值设置,会把外键设置为null,前提是允许为null。

SET_DEFAULT:此值设置,会把设置为外键的默认值。

SET():此值设置,会调用外面的值,可以是一个函数。

一般情况下使用CASCADE就可以了。

下面是官方文档说明:

ForeignKey accepts other arguments that define the details of how the relation works.

ForeignKey.on_delete ¶

When an object referenced by a ForeignKey is deleted, Django will emulate the behavior of the SQL constraint specified by the on_delete argument. For example, if you have a nullable ForeignKey and you want it to be set null when the referenced object is deleted:

user=models.ForeignKey(User,models.SET_NULL,blank=True,null=True,)

Deprecated since version 1.9: on_delete will become a required argument in Django 2.0. In older versions it defaults toCASCADE.

The possible values for on_delete are found in django.db.models :

CASCADE [source] ¶

Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey.

PROTECT [source] ¶

Prevent deletion of the referenced object by raising ProtectedError , a subclass of django.db.IntegrityError .

SET_NULL [source] ¶

Set the ForeignKey null; this is only possible if null isTrue.

SET_DEFAULT [source] ¶

Set the ForeignKey to its default value; a default for the ForeignKey must be set.

SET() [source] ¶

Set the ForeignKey to the value passed to SET() , or if a callable is passed in, the result of calling it. In most cases, passing a callable will be necessary to avoid executing queries at the time your models.py is imported:

fromdjango.confimportsettingsfromdjango.contrib.authimportget_user_modelfromdjango.dbimportmodelsdefget_sentinel_user():returnget_user_model().objects.get_or_create(username='deleted')[0]classMyModel(models.Model):user=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.SET(get_sentinel_user),)

DO_NOTHING [source] ¶

Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQLONDELETEconstraint to the database field.

ForeignKey.limit_choices_to ¶

Sets a limit to the available choices for this field when this field is rendered using aModelFormor the admin (by default, all objects in the queryset are available to choose). Either a dictionary, a Q object, or a callable returning a dictionary or Q object can be used.

For example:

staff_member=models.ForeignKey(User,on_delete=models.CASCADE,limit_choices_to={'is_staff':True},)

causes the corresponding field on theModelFormto list onlyUsersthat haveis_staff=True. This may be helpful in the Django admin.

The callable form can be helpful, for instance, when used in conjunction with the Pythondatetimemodule to limit selections by date range. For example:

deflimit_pub_date_choices():return{'pub_date__lte':datetime.date.utcnow()}limit_choices_to=limit_pub_date_choices

Iflimit_choices_tois or returns a Qobject , which is useful for complex queries , then it will only have an effect on the choices available in the admin when the field is not listed in raw_id_fields in theModelAdminfor the model.

Note

If a callable is used forlimit_choices_to, it will be invoked every time a new form is instantiated. It may also be invoked when a model is validated, for example by management commands or the admin. The admin constructs querysets to validate its form inputs in various edge cases multiple times, so there is a possibility your callable may be invoked several times.

请教Python里的queryset是什么,以及Objects类的用法?

这是哪儿的django面试题目或者笔试题目吧,请查看django开发手册。

1.queryset是查询集,就是传到服务器上的url里面的查询内容。Django会对查询返回的结果集QuerySet进行缓存,这是为了提高查询效率。也就是说,在你创建一个QuerySet对象的时候,Django并不会立即向数据库发出查询命令,只有在你需要用到这个QuerySet的时候才会这样做。

2.Objects是django实现的mvc中的m,Django中的模型类都有一个objects对象,它是一个Django中定义的QuerySet类型的对象,它包含了模型对象的实例。

3.不能,因为get可能会有异常,可以用filter函数,如下

Entry.objects.filter(blog__id__exact=1)# 显示的使用__exact

Entry.objects.filter(blog__id=1)# 隐含的使用__exact Entry.objects.filter(blog__pk=1)# __pk 相当于 __id__exact

Django,objects.get和objects.filter的区别

踩坑记录

前提,models.py已有模型,如果ID存在则update其他字段,如果不存在则做add操作,一直进行add操作无法走到update,导致数据重复增加

1.django的objects.get()方法

omissionRate.objects.get(id=id)

通过get获取,返回的是一个记录对象,如果结果不存在或者是有多条结果,无法进入if语句下,直接跳到except

get()内参数允许多个,and的关系,需同时满足

2.django的 objects.filter()方法:

obi = omissionRate.objects.filter(id=id)[0]

通过filter返回的是一个对象列表,如果结果不存在会返回[]

总结:get方法只能取到一个对象,而filter方法可以取到多个对象get方法取不到对象的话就会报错,而filter方法则相反,它是返回一个空列表

Django中,Model.objects.create 和 Model 的区别

django的get和filter方法是django model常用到的,搞清楚两者的区别非常重要。

为了说明它们两者的区别定义2个models

class Student(models.Model):

name = models.CharField('姓名', max_length=20, default='')

age = models.CharField('年龄', max_length=20, default='')

class Book(models.Model):

student = models.ForeignKey(Student)

一.先说下django的get方法:

1django的get方法是从数据库的取得一个匹配的结果,返回一个对象,如果记录不存在的话,它会报错。

比如我数据库里有一条记录,记录的name的值是"Python"的话,我用student = Student.objects.get(name='老王python'),

返回的是一个记录对象,你可以通过student.__dict__来查看,它返回的是一个字典的形式,{'key':valeus},key是字段的名称,而values是值的内容。

而如果我用get方法来查询一个数据库里不存在的记录,程序会报错。

比如:student = Student.objects.get(name='老王'),你自己可以运行看下。

2如果你用django的get去取得关联表的数据的话,而关键表的数据如果多于2条的话也会报错。

比如我的student表里有一个记录:

id name age

1 python 24

book表:

id student_id

1 1

2 1

我用

student = Student.objects.get(name='python')

book = Book.objects.get(student)

它也会报错,因为book表有2条记录和student表相匹配。

二.再说下django filter:

1django的filter方法是从数据库的取得匹配的结果,返回一个对象列表,如果记录不存在的话,它会返回[]。

比如我数据库里有一条记录,记录的name的值是Python的话,我用student = Student.objects.filter(name='老王python')

它返回的student是一个对象的列表,可以看的出来student[0]和上面的get方式返回的student的结果是一样的。

结语:以上就是首席CTO笔记为大家整理的关于哪个版本的Django中objects的全部内容了,感谢您花时间阅读本站内容,希望对您有所帮助,更多关于哪个版本的Django中objects的相关内容别忘了在本站进行查找喔。


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:/Python/18349.html