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

yipeiwu_com7年前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加密自己的密码

有些时候我们不得不在自己的代码里写上密码,为了安全起见,我们可以为自己的密码加密 先上段代码,这个代码是转自网上 root@ProFtp:/usr/lib/python2.7# mo...

Python中判断输入是否为数字的实现代码

在接收raw_input方法后,判断接收到的字符串是否为数字 例如: str = raw_input("please input the number:") if str.isdig...

Python time模块详解(常用函数实例讲解,非常好)

Python time模块详解(常用函数实例讲解,非常好)

在开始之前,首先要说明这几点: 1.在Python中,通常有这几种方式来表示时间:1)时间戳 2)格式化的时间字符串 3)元组(struct_time)共九个元素。由于Python的ti...

用Python PIL实现几个简单的图片特效

用Python PIL实现几个简单的图片特效

导入 numpy 、PIL numpy用来做矩阵运算,PIL用来读取图片。 import numpy as np from PIL import Image 读取图片,然后转换成R...

Python中操作符重载用法分析

本文实例讲述了Python中操作符重载用法。分享给大家供大家参考,具体如下: 类可以重载python的操作符 操作符重载使我们的对象与内置的一样。__X__的名字的方法是特殊的挂钩(ho...