2016-04-17 17 views
0

QuerySetのユーザー投稿をフィルタリングしようとすると、次のエラーが表示されます。投稿者はForeignKeyです。 Djangoは次の行に問題があります。Django Python:基数10のint()の無効なリテラル: 'arcetina'

posts = Post.objects.filter(author=components[0]) 

をし、このエラーを吐き出す:ここ

invalid literal for int() with base 10: 'arcetina' 

は私views.pyです:

def post_list(request): 
    global posts 

    context = {'posts' : posts} 

    for post in posts: 
     if not post.field: 
      post.field = 'Unspecified' 

    if request.method == "POST": 
     searchRegex = request.POST.get("searchregex") 
     components = searchRegex.split() 

     if searchRegex == "-reversedate": 
      posts = posts.reverse() 
      context = {'posts' : posts} 

     if "-user" in searchRegex: 
      posts = Post.objects.filter(author=components[0]) 

    return render(request, 'webapp/threadfeed.html', context) 

そして、ここでは私のmodels.pyです:

class Post(models.Model): 
    title = models.CharField(max_length=150) 
    slug = models.SlugField() 
    text = models.TextField() 
    created_on = models.DateTimeField(auto_now_add=True) 
    up_vote = 0 # num of up votes 
    down_vote = 0 #num of down votes 
    vote_total = up_vote - down_vote 
    author = models.ForeignKey('auth.User', null=True, blank=True) 

    CHOICES = [ 
     ('Hardware and OS', 'Hardware and OS'), 
     ('Desktops', 'Desktops'), 
     ('Tablets', 'Tablets'), 
     ('Phones', 'Phones'), 
     ('Wearables', 'Wearables'), 
     ('Windows', 'Windows'), 
     ('Mac OS X', 'Mac OS X'), 
     ('Linux and Unix', 'Linux and Unix'), 
     ('Programming and Computer Science', 'Programming and Computer Science'), 
     ('Software Development', 'Software Development'), 
     ('Web Development (Front)', 'Web Development (Front)'), 
     ('Web Development (Back)', 'Web Development (Back)'), 
     ('Mobile Development', 'Mobile Development'), 
     ('Game Development', 'Game Development'), 
     ('Algorithms and Data Structures', 'Algorithms and Data Structures'), 
     ('Databases', 'Databases'), 
     ('IDE/Text Editors', 'IDE/Text Editors'), 
     ('Tutorial', 'Tutorial'), 
     ('Opinion', 'Opinion'), 
     ('Miscellaneous', 'Miscellaneous') 
    ] 
    field = models.CharField(choices=CHOICES, max_length=200, default='Unspecified') 

    def __unicode__(self): 
     return self.title.encode('utf-8') 

    @models.permalink 
    def get_absolute_url(self): 
     return ('blog_post_detail',(), 
       { 
        'slug' :self.slug, 
       }) 

    def save(self, *args, **kwargs): 
     if not self.slug: 
      self.slug = slugify(self.title) 
     super(Post, self).save(*args, **kwargs) 

答えて

1

エラーが示すように、文字列を渡して整数のフィールドをフィルタリングしています。 (実際には外部キーだが、それは、整数IDとして格納されます。)

あなたは、関連するモデルのフィールドにフィルタを適用する場合は、二重アンダースコアの構文を使用する必要があります。

posts = Post.objects.filter(author__username=components[0]) 

グローバルpostsクエリーセットを持つことは、特にあなたの視点で突然変異させているときには、非常に悪い考えです。すべてのリクエストに同じリストが表示されます。ユーザーによってそれをフィルタリングしたり、逆にしたりすると、次のリクエストには既に変更されたクエリーセットが表示されます。グローバル変数を削除し、毎回投稿モデルをゼロから検索する必要があります。

関連する問題