Django IN查询作为字符串结果 - 对于带有基数10的int()的无效文字 [英] Django IN query as a string result - invalid literal for int() with base 10
问题描述
尝试查询收藏夹模型以获取用户所拥有的项目列表,然后针对不同的模型进行查询,以使该对象从该查询返回到模板,但是我收到错误:对于基数为10的int()的无效文字
Trying to query a 'Favorites' model to get a list of items a user has favorited, and then querying against a different model to get the objects back from that query to present to the template, but I'm getting an error: "invalid literal for int() with base 10"
查看该错误的所有其他实例,找不到任何asker实际想要的内容使用逗号分隔的整数列表,所以我有点失落。
Looking over all of the other instances of that error, I couldn't find any in which the asker actually wanted to work with a comma separated list of integers, so I'm kind of at a loss.
class Favorite(models.Model):
# key should be the model name, id is the model.id, and user is the User object.
key = models.CharField(max_length=255, unique=True)
val = models.IntegerField(default=0)
user = models.ForeignKey(User)
class Admin:
list_display = ('key', 'id', 'user')
查看
View
def index(request):
favorites = Favorite.objects.filter(key='blog', user=request.user.pk)
values = ""
for favorite in favorites:
values += "%s," % favorite.val
#values = "[%s]" % values
blogs = Blog.objects.filter(pk__in=values)
return render_to_response('favorite/index.html',
{
"favorites" : favorites,
"blogs" : blogs,
"values" : values,
},
context_instance=RequestContext(request)
)
enter code here
推荐答案
pk__in
不使用逗号分隔的字符串值列表,它实际上需要枚举(列表或元组)与值列表。相反,请执行以下操作:
The pk__in
doesn't take a string with a comma separated list of values, it actually takes an enumerable (a list or tuple) with the list of values. Instead, do something like this:
values = [favorite.val for favorite in favorites]
而不是循环的循环。我认为这应该修复你已经有了,但是由于你没有发布追踪或错误的行,我无法完全确定。
Instead of the for
loop you've got. I think that should fix what you've got but since you didn't post the traceback or what line it errors on I can't be totally sure.
在 IntegerField
中存储来自另一个表的ID,您应该真正考虑将其重构为外键,如果这是可能的话。
Also instead of storing the ID from another table in an IntegerField
you should really consider just refactoring that to be a foreign key instead, if that's at all possible.
这篇关于Django IN查询作为字符串结果 - 对于带有基数10的int()的无效文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!