博客
关于我
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',    }}

模型创建

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

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/

你可能感兴趣的文章
npm报错Cannot find module ‘webpack‘ Require stack
查看>>
npm报错Failed at the node-sass@4.14.1 postinstall script
查看>>
npm报错fatal: Could not read from remote repository
查看>>
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错TypeError: this.getOptions is not a function
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用操作---npm工作笔记003
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>
npm配置安装最新淘宝镜像,旧镜像会errror
查看>>
NPM酷库052:sax,按流解析XML
查看>>
npm错误 gyp错误 vs版本不对 msvs_version不兼容
查看>>