如何通过外键过滤查询?

时间:2019-01-24 12:17:39

标签: python django model

我试图在DirectorDetailView中获取按其“导演”过滤的“鹈鹕”列表

我找不到正确的语法来做到这一点。 Django版本: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”

你们好!

1 个答案:

答案 0 :(得分:0)

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

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

您可以完全删除get_context_data方法。