django如何反序列化外键字段?

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

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 插入多对多数据

django如何反序列化外键字段?  第1张

关于django数据库设计,双表互为外键

数据库设计是整个设计最基础的部分

1、django app的设计:根据系统的需求分析来设计django的app,django的开发是基于app来开发的,所以第一步就是设计app。

2、各app model 的设计:也就是设计对应的数据表

3、数据表的生成以及修改

使用在线教育系统作为实例:

userprofile的设计:在任何一个系统中,user表都是第一个被设计的,django会产生几个默认用户数据表

在设计我们自己的user表的时候,我们希望能生成自己的表又希望能够继承django的默认表,此时,我们可以继承AbstractUser(

from django.contrib.auth.models import AbstractUser

class UserProfile(AbstractUser):

pass

定义完UserProfile表之后,我们需要在setting.py文件中注册users app,INSTALLED_APPS = [

\'users\',

]

并且定义一个方法AUTH_USER_MODEL = \"users.UserProfile\",注意这里是使用users.UserProfile而不是users.model.UserProfile

(1)user model的设计:

我们在设计django app的时候,每个app中都有model,model文件中很有可能用到其他app文件当中的model,这就会很容易引入循环引用的问题,为了解决这个问题,很常用的一种方法就是使用分层model的方法,也就是上一层可以引用下一层

的model,如下:

注:PEP8的在引入的规范是第一个区域是导入Python自带的包,然后隔一行的第二个区域是第三方的包,如django,然后隔一行的第三个区域是我们自己定义的一些model

(2)course model 的编写:一个数据可能和另一个数据是一对多的关系,但是一张表存储不了这种关系,所以就需要把这两个数据分别存储在不同的数据表当中,这样就会引入外键的关系。

model的FileFIield,定义了这个字段就可以在后台系统中生成上传文件的按钮

(3)oganization model的编写:

(4)operation的model编写:

所有的APP编写完成之后,我们可以建立Python的apps包,把所有的app都放到这个apps中,把所有的APP放到apps之后,会发现各个app的model的引用可能会出现红线,说明我们找不到这些引用的包,所以需要我们在setting.py文件当中

把apps加入Python的搜索目录之下,

import syssys.path.insert(0, os.path.join(BASE_DIR, \'apps\'))

django model里怎么实现外键对多种model

首先题主用的Django版本是什么,django貌似没见过ForeignModel,根据orm,ForeignKey实际上就是sql里面的外键,个人理解楼主的题目是能不能一个字段对应多个其他表,如下:

class WhatAreYouTryToAsk:

filed_XXX = models.ForeignKey((ModelA,ModelB,))

这是不科学的啊亲,对于sql来说也不会一个字段能对应多个外键,想实现这种效果只能是有一张ModelA,ModelB的中间表,而filed的外键对应这张中间表

class MiddleTable(models.Model):

model_a = models.ForeignKey(ModelA)

model_b = models.ForeignKey(ModelB)

class WhatAreYouTryToAsk:

filed_XXX = models.ForeignKey(MiddleTable)

简单的说就是ModelA和ModelB有一个多对多的关系,上面的方法是显示的指明一个MiddleTable表,实时上可以使用Django里面的ManyToMany,ManyToMany的实际上会建一张中间表,因此你可以在ModelA或ModelB建立一个ManyToMany的字段,具体ManyToMany的用法请查阅文档。

class ModelA(models.Model):

model_bs = ManyToMany(ModelB)

class WhatAreYouTryToAsk:

filed_XXX = models.ForeignKey(ModelA)

# or this, 具体实现看需求

# filed_XXX = models.ForeignKey(ModelB)

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.

Django的orm中怎么让外键字段不加_id

外键在数据库中的默认字段名是它在模型中的属性名+_id。可以在创建外键时使用db_column参数显式地指定一个字段名,来覆盖这么默认字段名。

author = models.ForeignKey(\'Author\', on_delete=models.CASCADE, db_column=\'foobar\')

那么数据库中这个外键字段名就是foobar,而不是author_id。

结语:以上就是首席CTO笔记为大家介绍的关于django如何反序列化外键字段的全部内容了,希望对大家有所帮助,如果你还想了解更多这方面的信息,记得收藏关注本站。

以上内容为新媒号(sinv.com.cn)为大家提供!新媒号,坚持更新大家所需的互联网后端知识。希望您喜欢!

版权申明:新媒号所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流,不声明或保证其内容的正确性,如发现本站有涉嫌抄袭侵权/违法违规的内容。请发送邮件至 k2#88.com(替换@) 举报,一经查实,本站将立刻删除。

(0)
上一篇 2023-09-23 13:56
下一篇 2023-09-23 13:56

相关推荐

发表回复

登录后才能评论