首页>>后端>>Python->django不使用外键怎么跨表(2023年最新整理)

django不使用外键怎么跨表(2023年最新整理)

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

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

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的管理页面怎么显示和过滤另外一个表的字段,非外键

一个表的外键关联到主表的主键约束或者unique约束都可以,不一定非要主键约束

Django表关联对象及多表查询

首先建立Student,Dpartment,Course,Stu_info表

一对多表关系数据的添加:

1.第一种方式就是跟之前的一样,用传参的方法添加,需要注意的是外键的值必须是关联表中已经存在的值.

2.第二种方式是用的属性赋值的方式,因为我们在模型类有定义了一个department的属性,而这个属性的对象的类型必须是department表的类实例对象

表关联对象的访问:

Student的模型类中我们有定义department的属性,所以当我们去访问的时候,可以直接通过student.department的形式去找到某个学生的所属学院是哪个.

那么如果我们也希望在在访问某个学院的实现对象的学生的时候改怎么访问呢???

表关联对象的访问:

可以在定义时设置related_name 参数来覆盖foo_set 的名称.

clear() 从关联的对象集中删除所有的对象

多表查询----跨关联关系的查询:

Django 提供一种强大而又直观的方式来“处理”查询中的关联关系,它在后台自动帮你处理JOIN。 若要跨越关联关系,只需使用关联的模型字段的名称,并使用双下划线分隔,直至你想要的字段:

它还可以反向工作。若要引用一个“反向”的关系,只需要使用该模型的小写的名称。

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)

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


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