我需要得到导演导演的“电影”(Peliculas)的数量。电影和导演是不同的课程。感谢一位 stackoverflow 用户,我能够从模板中做到这一点,但我认为当我们谈论两个模型类时可能会有所不同。我想在 Director 中创建一个函数,告诉我他做了多少部电影,但我不知道如何从“Director”中调用“Peliculas”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' ) def get_num_peliculas(self): n_peliculas = Pelicula.object.all().count #NOT WORKING return n_peliculasclass 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') ) actores = models.ManyToManyField( Actor, blank=True )我怎样才能做到这一点?
1 回答
温温酱
TA贡献1752条经验 获得超4个赞
您可以反向查询关系pelicula_set,例如:
class Director(models.Model):
# ...
def get_num_peliculas(self):
return self.pelicula_set.count()
如果您related_name=...在ForeignKey指向主管中指定了 a ,那么这就是反向关系的名称。
或者,您可以.filter(..)使用查询集,这基本上就是这种反向关系所发生的情况:
class Director(models.Model):
# ...
def get_num_peliculas(self):
return Pelicula.objects.filter(director=self).count()
添加回答
举报
0/150
提交
取消