Django:获取特定用户的所有对象

时间:2017-12-01 16:08:02

标签: python django listview django-queryset django-related-manager

尝试显示用户的所有 Announce 对象时出现问题。 我的问题是:考虑我以id = 1的用户身份登录。当我转到 / users / 1 / 时,它会显示我的所有帖子。但问题是当我想通过转到/ users / 2 /来显示id = 2的其他用户的所有帖子时,它仍会显示我的所有Announce对象,而不是id = 2的用户。

models.py

class Announce(models.Model):
    owner        = models.ForeignKey('auth.User', related_name='announces')
    created_date = models.DateTimeField(auto_now_add=True)
    body         = models.TextField(max_length=1000)

views.py

class UserAnnouncesList(ListView):
    model = Announce
    template_name = 'myApp/user_announces_list.html'
    context_object_name = 'all_announces_by_user'

    def get_queryset(self):
        return Announce.objects.filter(owner=self.request.user)

urls.py

urlpatterns = [
url(r'users/(?P<pk>[0-9]+)/$', views.UserAnnouncesList.as_view(), name='user_announces_list'),]

user_announces_list.html

{% extends "account/base.html" %}

{% block content %}
{% for announce in all_announces_by_user %}
<h1>{{announce.user.username}}</h1>
    <p>{{announce.body}}</p>

{% endfor %}
{% endblock content %}

我是否必须使用某种类似的方式:Announce.objects.get(pk = ???)?

感谢您的帮助!

1 个答案:

答案 0 :(得分:8)

request.user是登录的用户。您需要使用作为网址传递的pk 。它存储在listview的kwargs字典中:

class UserAnnouncesList(ListView):
    model = Announce
    template_name = 'myApp/user_announces_list.html'
    context_object_name = 'all_announces_by_user'

    def get_queryset(self):
        return Announce.objects.filter(owner=self.kwargs['pk'])