2017-02-24 51 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})