首页>>后端>>Python->django外键怎么保存(django不使用外键)

django外键怎么保存(django不使用外键)

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

本篇文章首席CTO笔记来给大家介绍有关django外键怎么保存以及django不使用外键的相关内容,希望对大家有所帮助,一起来看看吧。

本文目录一览:

1、django如何设置外键2、Django中对于上传的文件的保存方法(时间+文件名)3、django 2.0外键处理

django如何设置外键

先给data赋值了之后,再去用p保存。例如:

data=Lessonruntime()

data.***=*** #(给data的列赋值)

data.save() #保存data(注,只有在新建data数据时才要,否则用 Lessonruntime.object.get()来获取data的值)

p = Checkinlog(lessonruntimeid=data)

p.save()

这样就可以了。

不可以用 p = Checkinlog(lessonruntimeid=1134)的方式进行赋值。

Django中对于上传的文件的保存方法(时间+文件名)

        这是在windows环境下,且要加入上传时间,与本来的文件名拼在一起,形成一个整个的文件名,所以,其必须将文件名放在最后,而将时间放在前面,避免与后缀名冲突,除此之外,还要使用time.time()方法,取得时间戳(格式化时间会与windows系统产生冲突),并且最好进行取整,然后再将其转化为字符串与文件名拼起来组成新的文件名,从而进行保存。实例如下:

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.

结语:以上就是首席CTO笔记为大家介绍的关于django外键怎么保存和django不使用外键的全部内容了,希望对大家有所帮助,如果你还想了解更多这方面的信息,记得收藏关注本站。


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