A
A
Alexander Savchuk2015-05-24 18:24:15
Django
Alexander Savchuk, 2015-05-24 18:24:15

How to display related objects in a separate ListView?

Good afternoon!
I can't figure out how to do it right.
Let's say we have the following models:

class Post(models.Model):
    ...

class Comment(models.Model):
    ...
    post = models.ForeignKey(Post)

To display a list of posts, use:
class PostListView(ListView):
    model = Post

Comments for each post should be displayed on a separate page, for example, for a post with ID 2, this is: /posts/2/comments/
At the moment, the comment list view looks like this:
# views.py

class CommentListView(ListView):
    model = Comment
    
    def get_queryset(self):
        return Comment.objects.filter(post=self.kwargs.get('post_pk'))

# urls.py
url(r'^post/(?P<post_pk>\d+)/comments/$', CommentListView.as_view(), name='comment-list')

It seems to work, but what if you need to organize a more complex structure. For example /countries/1/regions/3/city/2 ? Do everything by hand?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman Kitaev, 2015-05-24
@MrLinch

Well, yes. Add the rest manually in get_context_data.
By the way, I advise you to replace get_queryset with:

def get_queryset(self):
    return super().get_queryset().filter(post=self.kwargs.get('post_pk'))

S
Stanislav Fateev, 2015-05-24
@svfat

If I understood you correctly, then for /countries/1/regions/3/city/2 in urls.py there should be something like
And redo the get_queryset method accordingly

A
Alexander Pinkevich, 2015-05-24
@pinkevich

django-filter

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question