作用:
- 两个数据库表建立外键关系
- 当外键表的数据被删除时,主表的数据也会一并删除。
1,添加表模型
Test/app8/views.py
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50, unique=True)
email = models.EmailField(unique=True)
password = models.CharField(max_length=128) # 使用哈希存储密码
first_name = models.CharField(max_length=60)
last_name = models.CharField(max_length=50)
# 添加其他字段,例如:
# age = models.IntegerField()
# bio = models.TextField()
# ...
class Meta:
db_table = 'users2'
def __str__(self):
return self.username
class Person(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
def __str__(self):
return self.name
class Passport(models.Model):
person = models.OneToOneField(Person, on_delete=models.CASCADE)
passport_number = models.CharField(max_length=20)
issue_date = models.DateField()
def __str__(self):
return f"{self.passport_number} - {self.person.name}"
2,执行迁移命令
python manage.py makemigrations app8
python manage.py migrate app8
使用迁移命令会生成Person和Passport两个张模型表,Passport表中生成一个外键,命名为person_id
3,执行测试脚本增加数据库表实例
Test/scripts.py
# create_instances.py
import os
import django
from datetime import date
# 设置 Django 环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Test.settings')
django.setup()
from app8.models import Person, Passport
# 创建一个 Person 实例
person = Person.objects.create(name="test2", age=30)
# 创建一个 Passport 实例,并关联到上面的 Person 实例
passport = Passport.objects.create(person=person, passport_number="A12345678", issue_date=date(2023, 6, 30))
# 打印结果
print(f"Created Person: {person.name}, Age: {person.age}")
print(f"Created Passport: {passport.passport_number}, Issue Date: {passport.issue_date}")
分别执行脚本,创建了两条数据
4,添加视图函数
Test/app8/views.py
from django.shortcuts import render
from .models import User
def create_user(request):
if request.method == 'POST':
username = request.POST.get('username')
email = request.POST.get('email')
# ... 获取其他字段的值
# 创建用户实例
user = User(
username=username,
email=email,
# ... 填充其他字段
)
user.save() # 保存到数据库
# ... 处理成功或失败的逻辑
return render(request, '8/1.html')
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from app8.models import Person, Passport
def delete_person(request, person_id):
person_to_delete = get_object_or_404(Person, id=person_id)
person_to_delete.delete()
return HttpResponse("Person and associated Passport have been deleted.")
5,添加路由地址
from django.urls import path
from . import views
urlpatterns = [
path('create_user', views.create_user, name='create_user'),
path('delete_person/<int:person_id>/', views.delete_person, name='delete_person'),
]
6,访问页面,删除person数据示例
http://127.0.0.1:8000/app8/delete_person/2/
查看数据库,app8_passport,app8_person表,person_id 为2的数据被删除了
通过对比数据可以看到,通过路由传递的person_id为2时,数据库app8_passport表对应的person_id为2的数据被删除了,app8_person表id为2的数据也一并被删除了。
本文已有实现删除数据示例,以下是插入数据,展示数据示例补充内容:
Django 模型创建的两表插入数据-CSDN博客
Django 页面展示模型创建表的数据-CSDN博客