【问题标题】:Django query isn't returning id value as an integerDjango 查询没有将 id 值作为整数返回
【发布时间】:2016-04-14 23:10:42
【问题描述】:

我正在从数据库表文章中提取一个主键,并尝试将其作为外键保存到数据库表注释中。我收到错误int() 参数必须是字符串或数字,而不是 'QuerySet'

我尝试将 article_id 转换为 int(article_id),但它返回相同的错误。我尝试将值拉入列表,但随后返回列表错误。我打印了查询 article_id 的值,并在终端返回[{'id': 1L}],这是数据库中的第一篇文章。

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

我正在使用 Python 2.7 和 django 1.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}))

【问题讨论】:

    标签: python mysql django foreign-keys


    【解决方案1】:

    将您的 filter() 呼叫替换为 get()

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

    filter() 方法返回一个queryset:与您的条件匹配的对象列表。要仅获取一个对象(您的意思是这样,对吗?),您应该调用 get()

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

    【讨论】:

    • 谢谢你的作品,有人应该在文档中放一个例子:docs.djangoproject.com/es/1.9/topics/db/queries/…
    • 我敢打赌,SO 的答案通常比 Google 的官方文档排名更好,所以这不一定是问题。如果它适合您,请考虑将此答案标记为已接受。
    猜你喜欢
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 2019-06-28
    相关资源
    最近更新 更多