Django查询未将id值作为整数返回

2024-10-01 15:40:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我从db table文章中提取一个主键,并尝试将其作为外键保存到db tablecomment中。我收到错误int()参数必须是字符串或数字,而不是“QuerySet”

我尝试将article_id强制转换为int(article_id),但它返回相同的错误。我试着把值拉到一个列表中,但是它返回一个列表错误。我已经打印了查询的值article\uid,并在终端中返回[{'id': 1L}],这是数据库中的第一篇文章。在

这种插入外键的方法在更新记录时有效,但现在在创建记录时就不行了。如何插入外键?

我使用的是python2.7和django1.9

if request.POST.get("ComentForm") is not None:       
    if InsertComent.is_valid():

        article_id = Article.objects.filter(title = Slug).filter(pub_date = aTimestamp).values("id")
        article_id = article_id
        user_id = request.user.id

        p=Comment(comment=InsertComent.cleaned_data['comment'], article_id=article_id, user_id=user_id)
        p.save()

        messages.add_message(request, messages.SUCCESS,
                            "Thanks for commenting!", extra_tags="ComentForm"                                    
                            )
        return HttpResponseRedirect(reverse('Article',  kwargs={'aTimestamp':aTimestamp,'aSlug':aSlug}))

Tags: id列表dbifisrequest错误记录
1条回答
网友
1楼 · 发布于 2024-10-01 15:40:38

将您的filter()调用替换为get()

article_id = Article.objects.get(title=Slug, pub_date= aTimestamp).pk

filter()方法返回一个queryset:匹配条件的对象列表。只得到一个对象(你的意思是这样的,对吗?)你应该打电话给get()。在

不仅如此,get()将返回一个Modelinstance,而且您似乎只需要它的主键。所以上面的代码基本上就是这样做的。在

相关问题 更多 >

    热门问题