博客
关于我
django2.0演示mysql下的一对多增删查改操作
阅读量:143 次
发布时间:2019-02-28

本文共 1636 字,大约阅读时间需要 5 分钟。

Django ORM一对多关系实践指南

本文将详细介绍如何在Django框架中利用ORM对MySQL数据库进行一对多关系模型的操作,适合对Django ORM有一定了解的开发者。

环境配置

数据库设置

DATABASES = {    'default': {        'ENGINE': 'django.db.backends.mysql',        'NAME': 'test',        'HOST': '127.0.0.1',        'PORT': 3306,        'USER': 'root',        'PASSWORD': '123456',    }}

模型创建

我们需要创建两张表:Account和Contact。以下是模型代码:

from django.db import modelsclass Account(models.Model):    user_name = models.CharField(max_length=80)    password = models.CharField(max_length=255)    def __str__(self):        return "Account: %s" % self.user_nameclass Contact(models.Model):    account = models.ForeignKey(        Account,        on_delete=models.CASCADE,    )    mobile = models.CharField(max_length=20)    def __str__(self):        return "%s, %s" % (self.account.user_name, self.mobile)

数据库迁移

运行迁移命令:

python manage.py makemigrationspython manage.py migrate

输出结果如下:

Operations to perform:Apply all migrations: admin, app01, auth, contenttypes, sessionsRunning migrations:Applying contenttypes.0001_initial... OKApplying auth.0001_initial... OK...Applying app01.0001_initial... OK

ORM操作

创建数据

from app01 import models# 创建账户a1 = models.Account.objects.create(user_name='Rose')# 创建联系记录c1 = models.Contact.objects.create(account=a1, mobile='123456')c2 = models.Contact.objects.create(account=a1, mobile='654321')# 保存数据c1.save()c2.save()

查询数据

# 查询联系记录contacts = models.Contact.objects.all()# 按照ID查询c3 = models.Contact.objects.filter(pk=1)

修改数据

# 修改联系记录的手机号c2.mobile = '78910'c2.save()

删除账户

a1.delete()

注意事项

  • ForeignKey关系会在删除Account时自动删除关联的Contact记录。
  • 确保数据库权限正确,避免因权限问题导致操作失败。

以上操作展示了如何在Django ORM中对一对多关系模型进行 CRUD 操作,希望对您有所帮助!

转载地址:http://swgd.baihongyu.com/

你可能感兴趣的文章
python中打散数组shuffle
查看>>
Python中执行外部命令
查看>>
Python中拼接numpy数组-ChatGPT4o作答
查看>>
Python中提示:no module named 'PIL'
查看>>
Python中提示:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position
查看>>
python中数据类型存储_浅谈Python中的数据类型
查看>>
python中文件最重要的功能是什么-学 Python 都用来干嘛的?
查看>>
python中文版语言_高盛最新调查:Python超过汉语成为未来最重要技能,你准备学哪种编程语言?...
查看>>
Python中文问题SyntaxError
查看>>
Python中方括号和括号括起来的列表有什么区别?
查看>>
python中时间处理_Python中处理时间的几种方法小结
查看>>
Python中枚举串口(包括虚拟端口)的跨平台方法是什么?
查看>>
python中根号下a怎么写_python中根号怎么表示
查看>>
Python中正则表达式的巧妙使用
查看>>
Python中浮点数的二进制表示(位不是十六进制)
查看>>
Python中特殊函数和表达式 filter,map,reduce,lambda
查看>>
python中用socket检测端口_Python 用socket模块实现检测端口和检测web服务
查看>>
python中用于列表操作的plus和append有什么区别?
查看>>
python中用递归求和
查看>>
python中的@staticmethod
查看>>