博客
关于我
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/

你可能感兴趣的文章
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>