Django通过多对多中介表中的多个字段进行过滤 [英] Django filter through multiple fields in a many-to-many intermediary table

查看:201
本文介绍了Django通过多对多中介表中的多个字段进行过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的django项目中有以下模型:

I have the following models in my django project:

class Video(models.Model):
    media = models.ForeignKey(Media)

class Media(models.Model):
    title = models.CharField(max_length=255)
    formats = models.ManyToManyField(Format,through='MediaFormat',related_name='media',blank=True)

class Format(models.Model):
    title = models.CharField(max_length=50)

class MediaFormat(models.Model):
    status = models.IntegerField()
    format = models.ForeignKey(Format)
    media = models.ForeignKey(Media)

现在,我要过滤所有具有特定格式的视频,并且该格式的状态码为10(可以使用).我怎样才能做到这一点? (假设f是格式):

Now, I want to filter all videos which have a specific format, AND the status code for that format is 10 (ready to use). How can I do that? (assuming that f is the format):

f = Format.objects.get(pk=3)

我很想使用:

Video.objects.filter(media__formats=f, media__mediaformat__status=10)

但是,这将返回所有符合以下两个假设的视频:

But then, that would return all videos that matches both of these assumptions:

  • a)包含该特定格式,并且
  • b)包含状态为10的任何格式

我应该如何只过滤状态码为10的那些具有特定格式的内容?

How am I supposed to filter only those who have that specific format in a status code of 10?

谢谢!

推荐答案

现在,我想过滤所有具有特定格式的视频,然后 该格式的状态码为10(可以使用).我怎样才能做到这一点? (假设f是格式)

Now, I want to filter all videos which have a specific format, AND the status code for that format is 10 (ready to use). How can I do that? (assuming that f is the format)

您发布的代码将完全满足您的要求:

The code you posted will do exactly what you want:

Video.objects.filter(media__formats=f, media__mediaformat__status=10)

此文档记录在 filter()文档中:

This is documented in the filter() documentation:

在基础SQL中通过AND连接多个参数 声明.

Multiple parameters are joined via AND in the underlying SQL statement.

这篇关于Django通过多对多中介表中的多个字段进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆