SoFunction
Updated on 2024-10-29

Introduction to foreign key descriptions in django versions

Here is the code

class GroupInfos():
 uid = (primary_key=True)
 caption = (max_length=32, unique=True)
 ctime = (auto_now_add=True, null=True)
 uptime = (auto_now=True, null=True)

class UserInfos():
 username = (max_length=32, blank=True, verbose_name='Username')
 password = (max_length=64, help_text='text')
 email = (max_length=60)
 user_group = ('GroupInfos', to_field='uid', on_delete='CASCADE')

clarification

The first class creates a table with the name app_groupinfos

The second class creates a table with the name app_userinfos

1、ForeignKey Indicates the setting of the outer robustness

2、to_fieldIndicates the primary key of the foreign key association

3. on_delete has multiple options

After django2.0, when defining foreign keys and one-to-one relationships, you need to add the on_delete option, which is a parameter to avoid data inconsistency problems in two tables, or it will report errors:

TypeError: init() missing 1 required positional argument: ‘on_delete'

Examples:

user=(User)
owner=(UserProfile)

It needs to be changed to:

user=(User,on_delete=) -- in older versions this parameter () was the default value
owner=(UserProfile,on_delete=) -- in older versions this parameter () is the default value

Parameter Description:

on_delete has five selectable values: CASCADE, PROTECT, SET_NULL, SET_DEFAULT, and SET().

CASCADE: This value is set and is a cascade delete.

PROTECT: This value is set such that an integrity error is reported.

SET_NULL: This value setting will set the foreign key to null, provided it is allowed to be null.

SET_DEFAULT: This value setting will set to the default value of the foreign key.

SET(): this value is set and will call the outside value, which can be a function.

Usually using CASCADE is sufficient.

Then, at this time, a group will correspond to multiple users, which is a one-to-many type.

The current outer robustness is used when we query a group for those users, the

Creating Records

Moreover, after defining the foreignKey in the class, the user table cannot be created because of the constraint that the group does not exist yet.

Deletion of records

Moreover, after defining the foreignKey in the class, while the records in the user exist, the records in the group table cannot be deleted because of the constraints.

Additional knowledge:owner = (User)TypeError appeared

owner = (User)error TypeError: init() missing 1 required positional argument: ‘on_delete'
owner = (User)

The following error occurs:

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

Solution:

owner = (User, on_delete=)

Above this django version of the () foreign key description of the introduction is all I have shared with you, I hope to give you a reference, and I hope you support me more.