Django 模型按外键过滤 [英] Django models filter by foreignkey

查看:26
本文介绍了Django 模型按外键过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在从一组模型中过滤对象时遇到了一些问题.问题来了:

I'm having some trouble in filtering objects from a set of models. Here is the problem:

我有 3 个班级:

class Autor(models.Model):    
    nome = models.CharField(max_length=50)
    slug = models.SlugField(max_length=50, blank=True, unique=True)
    foto = models.ImageField(upload_to='autores/', null=True, blank=True)
    ...

class CategoriaRecolha(models.Model):
    categoria = models.CharField(max_length=30)
    descricao = models.TextField()
    slug = models.SlugField(max_length=30, blank=True, unique=True)
    ...

class Recolha(models.Model):    
    titulo = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, blank=True, unique=True)
    descricao = models.TextField()
    ficha_tec = models.TextField()
    categoria = models.ForeignKey(CategoriaRecolha)
    autor = models.ForeignKey(Autor)
    ....

我要检索的是 Autor 类的字段,其中 Recolha 类的字段类别等于特定值.

What I'm trying to retrieve is the fields of the class Autor, in which the field categoria of the class Recolha is equal to a specific value.

以更简单的方式,我需要获取参与特定类别的所有作者.

In a more simple way, I need to get the all the autor that have participated in a specific categoria.

谢谢

推荐答案

更直接的替代方案:

autors = Autor.objects.filter(recolha__categoria=MyCategoria)

其中 MyCategoria 是相关的 CategoriaRecolha 实例.或者,如果您想再次匹配特定的类别名称,您可以将查询扩展到另一个级别:

where MyCategoria is the relevant CategoriaRecolha instance. Or, if you want to match agains the specific category name, you can extend the query another level:

autors = Autor.objects.filter(recolha__categoria__categoria='my_category_name')

这篇关于Django 模型按外键过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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