views:

174

answers:

2

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
+1  A: 

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.

Daniel DiPaolo
I'm trying to make it model agnostic, as I intend to allow users to 'favorite' many model types. I'm honestly too new to Django to know for certain if a ForeignKey is possible, but my guess is that unless I had an optional FKey for each model type that I wanted to extend, it isn't.
bmelton
The ContentTypes framework provides a "FKey for each model type". It is very uber.
T. Stone
I will take a look. In the meantime, Daniel's solution worked perfectly, though SO won't let me accept it for another three minutes. Thanks a million!
bmelton
+2  A: 

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 %}
T. Stone
Does it work the other way around? Can I attach the favorite object from a Blog object query? It would be super sweet to be able to test for blog.favorite, for example.
bmelton
Yes, as long as you've defined `favorite` as a `generic.GenericRelation` on those models (eg Blog) which you want to relate from.
Daniel Roseman