nested for loops inside templates

前端 未结 1 1827
耶瑟儿~
耶瑟儿~ 2021-01-28 08:09

models.py

class Task(models.Model):
     level = models.ForeignKey(Level, on_delete=models.CASCADE)
     todo = models.ForeignKey(ToDo, on_delete=models.CASCADE         


        
相关标签:
1条回答
  • 2021-01-28 08:44

    This line doesn't make any sense:

    images = Images.objects.filter(post=task)
    

    because task is a queryset of all the Task instances.

    You don't need to get the images at all in the view. Remove that line and the other references, and just do this in the template:

    {% for obj in task %}
        <p>{{ obj.title }}</p>
    
        {% for image in obj.images_set.all %}
          <img src="{{ image.image.url }}"</img> 
        {% endfor %}
    
    {% endfor %}
    

    Note also, the Image object has a field called image, and that's what you need to access the url attribute on.

    (For the sake of database efficiency, you might want to change your query slightly in the view:

    task = Task.objects.all().order_by('timestamp').prefetch_related('images_set')
    

    otherwise every iteration will cause a separate db call to get the related images. You don't need to do this to make things work, though.)

    0 讨论(0)
提交回复
热议问题