Django IN query as a string result - invalid literal for int() with base 10
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"
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.
Model
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
Something you might want to consider doing is converting this over to using the Django ContentTypes framework, which provides some nice syntatic sugar...
class Favorite(models.Model):
# former 'key' field
content_type = models.ForeignKey(ContentType)
# former 'value' filed
object_id = models.PositiveIntegerField()
# this gives access directly to the object that content_type+object_id represent
content_object = generic.GenericForeignKey()
user = models.ForeignKey(User)
Your view would then look like this:
def index(request):
favorites = Favorite.objects.filter(
content_type=ContentType.objects.get_for_model(Blog),
user = request.user
)
return render_to_response('favorite/index.html',
{ "favorites" : favorites, },
context_instance=RequestContext(request)
)
In your template, when you enumerate through favorites
, each model returned will have the .content_object
present which will be an instance of Blog
...
{% for fav in favorites %}
{# This would print the blog title for every favorite #}
{{ fav.content_object.title }}<br/>
{% endfor %}
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.
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.
精彩评论