Tho*_*ink 1 python mysql django foreign-keys
我从db表文章中提取主键并尝试将其作为外键保存到db表注释中.我收到错误: int()参数必须是字符串或数字,而不是'QuerySet'
我已经尝试将article_id作为一个int(article_id)但是它返回相同的错误.我已经尝试将值拉入列表但随后返回列表错误.我打印了查询article_id的值,并[{'id': 1L}]在终端中返回,这是db中的第一篇文章.
这种插入外键的方法在更新记录时起作用,但现在不是在创建记录时.如何插入外键?
我正在使用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}))
将您的filter()通话替换为get():
article_id = Article.objects.get(title=Slug, pub_date= aTimestamp).pk
该filter()方法返回一个查询集:符合条件的对象列表.要获得一个对象(你的意思是,对吗?)你应该打电话get().
更重要的是,get()它将返回一个Model 实例,你似乎只需要它的主键.这就是上面的代码基本上做的.
| 归档时间: | 
 | 
| 查看次数: | 1720 次 | 
| 最近记录: |