1

尝试查询“收藏夹”模型以获取用户收藏的项目列表,然后查询不同的模型以从该查询中获取对象以呈现给模板,但我收到错误:“无效以 10 为底的 int() 的字面量"

查看该错误的所有其他实例,我找不到提问者实际上想要使用逗号分隔的整数列表的任何实例,所以我有点不知所措。

模型

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')

看法

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
4

2 回答 2

2

您可能想要考虑做的事情是将其转换为使用 Django ContentTypes 框架,它提供了一些不错的语法糖......

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)

您的视图将如下所示:

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)
    )

在您的模板中,当您枚举 through 时favorites,返回的每个模型都将具有.content_object当前,这将是Blog...

{% for fav in favorites %}
    {# This would print the blog title for every favorite #} 
    {{ fav.content_object.title }}<br/>
{% endfor %}
于 2010-04-16T02:34:55.513 回答
1

不采用pk__in带有逗号分隔值列表的字符串,它实际上采用带有值列表的可枚举(列表或元组)。相反,请执行以下操作:

values = [favorite.val for favorite in favorites]

而不是for你得到的循环。我认为这应该可以解决您所拥有的问题,但是由于您没有发布回溯或错误发生在哪一行,因此我不能完全确定。

IntegerField此外,如果可能的话,您应该考虑将其重构为外键,而不是将另一个表中的 ID 存储在其中。

于 2010-04-16T02:27:51.687 回答