Django ManyToManyField 跨越中间表查询的方法

yipeiwu_com5年前Python基础

1、在 django 表中用到了 manytomany 生成了中间表 pyclub_article_column

from django.db import models

# Create your models here.

class Column(models.Model):
 id = models.AutoField(u'序号',primary_key=True,auto_created=True)
 name = models.CharField(u'名字',max_length=100)
 published = models.DateField(u'发布时间',auto_now_add=True)

 def __str__(self):
 return self.name

 class Meta:
 verbose_name = '栏目'
 verbose_name_plural = '栏目列表'
 ordering = ['id'] # 按照哪个栏目排序

class Article(models.Model):
 id = models.AutoField(u'序号',primary_key=True,auto_created=True)
 title = models.CharField(u'标题',max_length=100,default='')
 content = models.TextField(u'内容',default='')
 column = models.ManyToManyField(Column,verbose_name='归属栏目')
 published = models.DateField(u'发布时间',auto_now_add=True,null=True)

 def __str__(self):
 return self.title

 class Meta:
 verbose_name = '文章'
 verbose_name_plural = '文章列表'
 ordering = ['id'] # 按照哪个文章排序

2、生成了中间表 pyclub_article_column

+-----+------------+-----------+
| id | article_id | column_id |
+-----+------------+-----------+
| 370 | 411 | 146 |
| 371 | 412 | 146 |
| 372 | 413 | 165 |
| 373 | 414 | 158 |
| 374 | 415 | 151 |

3、我想通过column_id 获得 对应栏目列表中的所有数据列表,原先一直在怎么使用中间表这个问题上,一直搞不会,现在明白了,原来 结果集 column本身也可以作对象,那么,问题简单了

list_info = Article.objects.filter(column=id)

虽然article表中,没有column,但在django model.py通过many to many 已经建立起了对应关系,所以在view.py中,通过article objects时,可以直接使用filter进行类别查询。

以上这篇Django ManyToManyField 跨越中间表查询的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python使用Matplotlib实现雨点图动画效果的方法

Python使用Matplotlib实现雨点图动画效果的方法

本文实例讲述了Python使用Matplotlib实现雨点图动画效果的方法。分享给大家供大家参考,具体如下: 关键点 win10安装ffmpeg animation函数使用 update...

Python eval的常见错误封装及利用原理详解

最近在代码评审的过程,发现挺多错误使用eval导致代码注入的问题,比较典型的就是把eval当解析dict使用,有的就是简单的使用eval,有的就是错误的封装了eval,供全产品使用,这引...

python按照多个条件排序的方法

对tuple进行排序,先按照第一个元素升序,如果第一个元素相同,再按照第二个元素降序排列。 L = [(12, 12), (34, 13), (32, 15), (12, 24),...

python检查序列seq是否含有aset中项的方法

本文实例讲述了python检查序列seq是否含有aset中项的方法。分享给大家供大家参考。具体实现方法如下: # -*- coding: utf-8 -*- def contains...

python中count函数简单用法

python中count函数的用法 Python count()方法 描述 Python count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。...