django怎么设置外键(django自定义命令)

如题所述

第1个回答  2024-09-05

导读:今天首席CTO笔记来给各位分享关于django怎么设置外键的相关内容,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

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插入外键值思路

1.先确定需要添加添加的带有外键的数据格式,涉及几个表

2.前端组装好这个数据格式传回后端

3.后端验证数据,从请求中分离出外键的值,进行获取对象

4.使用add进行添加外键的值

r1=Role.objects.get(role_name=role)#r1表示UserInfo的多对多数据

u1=UserInfo(user_name=name,user_pwd=password,sex=sex,mobileno=mobile,email=email)

u1.save()

u1.role.add(r1)

u1.save()

django插入多对多数据

django2.0外键处理

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

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

TypeError:__init__()missing1requiredpositionalargument:'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就可以了。

下面是官方文档说明:

ForeignKeyacceptsotherargumentsthatdefinethedetailsofhowtherelationworks.

ForeignKey.on_delete?

WhenanobjectreferencedbyaForeignKeyisdeleted,DjangowillemulatethebehavioroftheSQLconstraintspecifiedbytheon_deleteargument.Forexample,ifyouhaveanullableForeignKeyandyouwantittobesetnullwhenthereferencedobjectisdeleted:

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

Deprecatedsinceversion1.9:on_deletewillbecomearequiredargumentinDjango2.0.InolderversionsitdefaultstoCASCADE.

Thepossiblevaluesforon_deletearefoundindjango.db.models:

CASCADE[source]?

Cascadedeletes.DjangoemulatesthebehavioroftheSQLconstraintONDELETECASCADEandalsodeletestheobjectcontainingtheForeignKey.

PROTECT[source]?

PreventdeletionofthereferencedobjectbyraisingProtectedError,asubclassofdjango.db.IntegrityError.

SET_NULL[source]?

SettheForeignKeynull;thisisonlypossibleifnullisTrue.

SET_DEFAULT[source]?

SettheForeignKeytoitsdefaultvalue;adefaultfortheForeignKeymustbeset.

SET()[source]?

SettheForeignKeytothevaluepassedtoSET(),orifacallableispassedin,theresultofcallingit.Inmostcases,passingacallablewillbenecessarytoavoidexecutingqueriesatthetimeyourmodels.pyisimported:

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]?

Takenoaction.Ifyourdatabasebackendenforcesreferentialintegrity,thiswillcauseanIntegrityErrorunlessyoumanuallyaddanSQLONDELETEconstrainttothedatabasefield.

ForeignKey.limit_choices_to?

SetsalimittotheavailablechoicesforthisfieldwhenthisfieldisrenderedusingaModelFormortheadmin(bydefault,allobjectsinthequerysetareavailabletochoose).Eitheradictionary,aQobject,oracallablereturningadictionaryorQobjectcanbeused.

Forexample:

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

causesthecorrespondingfieldontheModelFormtolistonlyUsersthathaveis_staff=True.ThismaybehelpfulintheDjangoadmin.

Thecallableformcanbehelpful,forinstance,whenusedinconjunctionwiththePythondatetimemoduletolimitselectionsbydaterange.Forexample:

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

Iflimit_choices_toisorreturnsaQobject,whichisusefulforcomplexqueries,thenitwillonlyhaveaneffectonthechoicesavailableintheadminwhenthefieldisnotlistedinraw_id_fieldsintheModelAdminforthemodel.

Note

Ifacallableisusedforlimit_choices_to,itwillbeinvokedeverytimeanewformisinstantiated.Itmayalsobeinvokedwhenamodelisvalidated,forexamplebymanagementcommandsortheadmin.Theadminconstructsquerysetstovalidateitsforminputsinvariousedgecasesmultipletimes,sothereisapossibilityyourcallablemaybeinvokedseveraltimes.

结语:以上就是首席CTO笔记为大家整理的关于django怎么设置外键的相关内容解答汇总了,希望对您有所帮助!如果解决了您的问题欢迎分享给更多关注此问题的朋友喔~

logo设计

创造品牌价值

¥500元起

APP开发

量身定制,源码交付

¥2000元起

商标注册

一个好品牌从商标开始

¥1480元起

公司注册

注册公司全程代办

¥0元起

    官方电话官方服务
      官方网站八戒财税知识产权八戒服务商企业需求数字市场

相关了解……

你可能感兴趣的内容

大家正在搜

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网