django 外键model的互相读取方法

作者:JackieLee 时间:2021-06-16 20:54:51 

先设定一个关系模型如下:


from django.db import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
def __str__(self):  
 return self.name

class Author(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField()
def __str__(self):  
 return self.name

class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
authors = models.ManyToManyField(Author)
def __str__(self):  
 return self.headline

上面的数据关系很明晰,Entry中有Blog和Author的外键,如果要在Entry中读取blog和author的数据很容易:


entry = Entry.objects.all()
for e in entry:
blog = e.blog
author = e.authors

要在Blog和Author中读取Entry也可以:


blog = Blog.objects.all()
entry = blog.entry_set.all()

author = Author.objects.all()
entry = author.entry_set.all()

下面通过entry使blog和author互相读取,比如要知道一个blog的Author只需如下:


blogs = Blog.objects.all()
for blog in blogs:
if blog.name== “我们想要查询的博客的name”
 author = blog. entry_set.authors

要查询一个author的所有blog如下:


authors = Author.objects.all()
blogs = []

for author in authors:
if author.name== “我们想要查询的Author的name”
 for entry in author.entry_set.all():
  blogs.append(entry. blog)

来源:https://blog.csdn.net/JackieLeeWelas/article/details/50311077

标签:django,model,读取
0
投稿

猜你喜欢

  • jupyter notebook 恢复误删单元格或者历史代码的实现

    2022-03-03 16:13:45
  • Python最长公共子串算法实例

    2022-08-11 01:29:57
  • 清除SQL被注入恶意病毒代码的语句

    2010-03-03 09:59:00
  • JS实现css边框样式设置工具

    2008-05-25 16:22:00
  • 使用Pytorch搭建模型的步骤

    2022-03-05 21:28:38
  • python发送邮件的实例代码(支持html、图片、附件)

    2023-08-31 00:39:50
  • Python学习笔记之函数的定义和作用域实例详解

    2021-09-09 11:05:30
  • asp金额大小写转换完全无错版

    2007-09-26 09:38:00
  • 详解Python 多线程 Timer定时器/延迟执行、Event事件

    2022-09-04 11:12:52
  • PHP设计模式 注册表模式(多个类的注册)

    2023-11-20 06:45:13
  • 在MySQL中使用XML数据—数据格式化

    2009-12-29 10:26:00
  • 浅析SQL Server与Oracle数据库的区别

    2007-10-31 11:39:00
  • python基础之循环语句

    2022-03-14 23:00:53
  • Python随机函数库random的使用方法详解

    2021-06-07 16:16:23
  • 关于Torch torchvision Python版本对应关系说明

    2021-06-17 09:13:52
  • Python就将所有的英文单词首字母变成大写

    2023-09-21 10:44:35
  • 防止网站内容被人小偷和采集的ASP代码

    2007-10-02 13:04:00
  • python模块hashlib(加密服务)知识点讲解

    2022-11-30 20:38:20
  • pytest内置fixture使用临时目录流程详解

    2021-12-27 06:49:23
  • HTML与javascript中常用编码浅析

    2008-12-23 12:20:00
  • asp之家 网络编程 m.aspxhome.com