2017-02-24 47 views
0

我正在用Django创建一个社交平台。现在,我正在开发他们的个人资料页面,并希望最终用户能够通过他们自己的帖子查看时间表。这是我的Post模型:在Django视图中过滤模型对象

class Post(models.Model): 
    user = models.ForeignKey(User) 
    posted = models.DateTimeField() 
    content = models.CharField(max_length=150) 
    Likes = models.IntegerField() 

def __str__(self): 
    return self.user.username 

在我想筛选出当前用户创建的所有职位的看法。不过,我不断收到错误:

无效字面INT()基数为10: '管理员'

这是我的看法:

@login_required 
def profile_view(request): 
    all_posts = Post.objects.get(user=User.username).order_by('-posted') 
    return render(request, 'Dashboard/profiel.html', {'posts':all_posts}) 

我在做什么错?

+0

嘿@Acework!如果其中一个答案对您的问题做出了很好的回应,请继续并接受它作为正确答案! :) – Max

回答

0

您应该从request对象获取当前用户:

@login_required 
def profile_view(request): 
    all_posts = Post.objects.filter(user=request.user).order_by('-posted') 
    return render(request, 'Dashboard/profiel.html', {'posts':all_posts}) 
+0

感谢您的评论。现在它给了我错误“get()返回多于一个Post - 它返回2!”因为当前用户有2个帖子,为什么他不能有超过1个? – Acework

+0

用'filter()'替换get()'就像我上面的例子。 – flowfree

1

get()只能在查询返回1元。

在Django文档filterget中。谁是有趣的部分是:

Retrieving a single object with get()

filter() will always give you a QuerySet, even if only a single object matches the query - in this case, it will be a QuerySet containing a single element.

If you know there is only one object that matches your query, you can use the get() method on a Manager which returns the object directly:

因此,使用filter和使用与所有匹配的查询:

@login_required 
def profile_view(request): 
    all_posts = Post.objects.filter(user=request.user).order_by('-posted') 
    return render(request, 'Dashboard/profiel.html', {'posts':all_posts}) 

且模板中,您的查询就像一个列表,使用循环显示它1加1

2

您的方法三个误区:

  1. user Post上的属性等待用户的实例。在您的过滤器中,您比较了userUser.username,它是CharField。
  2. 用户不是当前请求的用户。当前请求的用户作为Django的Request-Response-Lifecycle的一部分附加在request对象上。
  3. 当您想要获取QuerySet而不是单个实例时,需要使用filter()而不是get(),请参阅Django docs进行查询。

例子:

@login_required 
def profile_view(request): 
    all_posts = Post.objects.filter(user=request.user).order_by('-posted') 
    return render(request, 'Dashboard/profiel.html', {'posts':all_posts})