如何通过外键过滤查询? [英] How can I filter a query by a foreign key?

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

问题描述

我想在DirectorDetailView中获取按其导演"过滤的鹈鹕"列表

I'm trying to get a list of "Peliculas" filtered by their "Director" in my DirectorDetailView

我找不到正确的语法来做到这一点. Django版本:2.1.4

I can't find the correct syntax to do this. Django Version: 2.1.4

#MODEL DIRECTOR

class Director(models.Model):
    nombre = models.CharField(
        max_length=100
    )
    fecha_nacimiento = models.DateField()
    fecha_defuncion = models.DateField(
        'Fallecido',
        null=True,
        blank=True,
    )
    foto = models.ImageField(
        upload_to='images/directores/',
        default='images/directores/sin_foto.jpg'
    )

#MODEL PELICULA

class Pelicula(models.Model):
    titulo = models.CharField(
        max_length=100
    )
    url_trailer = models.CharField(
        max_length=100
    )
    fecha = models.DateField()
    notas_posibles = (
        (1, 1),
        (2, 2),
        (3, 3),
        (4, 4),
        (5, 5)
    )
    nota = models.IntegerField(
        default=3,
        choices=notas_posibles
    )
    sinopsis = models.TextField(
        max_length=400,
        default="Sin sinopsis"
    )
    caratula = models.ImageField(
        upload_to='images/peliculas/caratulas',
        default='images/peliculas/caratulas/sin_caratula.jpg'
    )
    imagen_promocional = models.ImageField(
        upload_to='images/peliculas/imagenes_promocionales',
        default='images/peliculas/imagenes_promocionales/sin_imagen.jpg'
    )
    genero = models.ManyToManyField(
        Genero,
        blank=True,
        related_name='genero'
    )
    director = models.ForeignKey(
        Director,
        on_delete=models.SET('Sin Director')
    )

#MY VIEW

class DirectorDetailView(DetailView):
model = Director
template_name = "videoclub/director.html"

def get_context_data(self, **kwargs):  
    print(self.model)
    context = super(DirectorDetailView, self).get_context_data(**kwargs)
    context['peliculas'] = Pelicula.objects.all() #HERE
    return context

有了这个代码,我收到了所有的鹈鹕",但我只有一个人可以得到我所认为的导演.真的不知道我在做什么错.我什至不知道我是否必须使用"DetailView"

With this code i receive all the "Peliculas" but i only one to get those made by the Director of my view. Dont really know what i'm doing wrong. I dont even know if i have to do this with "DetailView"

你们好!

推荐答案

您根本不需要在视图中执行此操作;您可以在模板中完成.

You don't need to do this in the view at all; you do it in the template.

{{ director.nombre }}
{% for pelicula in director.pelicula_set.all %}
  {{ pelicula.titulo }}
  {{ pelicula.sinopsis }} # etc
{% endfor %}

您可以完全删除get_context_data方法.

这篇关于如何通过外键过滤查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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