如何关联两个对象列表?

时间:2017-11-19 10:15:09

标签: python html django templates view

我有两个与外键相关的模型,pregunta是一个特定的Comentario(评论)的问题。

models.py

class Comentario (models.Model):
    titulo = models.CharField(max_length=50)
    texto = models.CharField(max_length=200)
    autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE)
    fecha_publicacion = models.DateTimeField(auto_now_add=True)
    tag = models.ManyToManyField(Tags, blank=True)

    def __str__(self):
        return (self.titulo)

class Pregunta (models.Model):
    descripcion = models.CharField(max_length=150)
    autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE)
    fecha_pregunta = models.DateTimeField(auto_now_add=True)
    comentario_preguntado = models.ForeignKey(Comentario, null=True, blank=True)

    def __str__(self):
        return (self.descripcion)

我创建了一个视图,我只想显示有问题的评论和问题本身。我创建了两个对象列表,一个带有注释,另一个带有问题。问题是我想在模板中显示第一条评论及其问题,然后是下一条评论及其问题...... 我不知道这是否应该在模板中完成,或者我需要改变我的观点。

views.py

def responder(request):
    comment = Comentario.objects.filter(id__in=Pregunta.objects.all().values_list('comentario_preguntado')).filter(autor=request.user)
    question = Pregunta.objects.filter(comentario_preguntado__in=comment)
    return render(request, 'home/responder.html', {'comment': comment, 'question': question})

1 个答案:

答案 0 :(得分:0)

只需通过related_name关系的ForeignKey访问评论的preguntas:

def responder(request):
    # use __isnull to filter for comments with existing preguntas
    # use prefetch_related to minimize db hits
    # use plural name to be semantically sound ;)
    comments = Comentario.objects\
        .filter(pregunta_set__isnull=False, autor=request.user)\
        .prefetch_related('pregunta_set')
    return render(request, 'home/responder.html', {'comments': comments})

在模板中:

{% for comment in comments %}
    # display comment stuff
    {% for pregunta in comment.pregunta_set.all %}
        # display pregunta stuff
    {% endfor %}
{% endfor %}

related_nameprefetch_relatedisnull上的文档。