[Django]-Django queryset dict in dict across ForeignKey

2👍

If you are looking to do this at the view level there is no need to create an object which is exactly like a table. The great thing about the ORM is you can ‘navigate’ through it to get the data you want and need. So in your case you only need to query the Place model pulling out the data you need. You can do something like this:

view.py

def my_view(request):
    object_list = Place.objects.all()
    return render(request, 'template.html', {'object_list':object_list})

template.html

<table>
{% for item in object_list %}
    <tr>
        <td>{{ item.place_name }}</td>
        <td>{{ item.place_summary }}</td>
        <td>
            <ul>
            {% for pic in item.place_image %}
                <li>{{ pic.place_name }}</li>
            {% endfor %}
            </ul>
        </td>
    </tr>
{% endfor %}
</table>

Whilst you can improve this code just worry about getting to grips with the basics first.


Just some side notes to help improve your code and working with querysets.

In your models you do not need to prefix attributes with the model name. Just doing the following is fine:

class Place(models.Model):
    name = models.CharField(max_length=200)
    summary = models.TextField(max_length=1500, blank=True, null=True)
    ...

    def __unicode__(self):
        return self.name

0👍

As per the understanding I think this is the way to go:

Place.objects.all().values('place_name','place_summary','place_image')

and see it solves your purpose?

0👍

I guess you can access the Place_Image queryset from a Place instance like this:

place.place_image_set.all() # to retrieve all 

since django adds ‘_set’ to the field name for reverse relationship. You can change it by specifiying a different field name with related_name like this:

place_name = models.ForeignKey(Place, related_name='place_images') 
👤helado

Leave a comment