Django IN 查询作为字符串结果 - 以 10 为基数的 int() 的文字无效

发布于 2024-08-28 22:34:00 字数 1111 浏览 6 评论 0原文

尝试查询“收藏夹”模型以获取用户收藏的项目列表,然后查询不同的模型以从该查询返回对象以呈现给模板,但我收到错误:“无效以 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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你列表最软的妹 2024-09-04 22:34:01

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

values = [favorite.val for favorite in favorites]

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

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

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.

坏尐絯℡ 2024-09-04 22:34:00

您可能需要考虑做的事情是将其转换为使用 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)
    )

在您的模板中,当您通过 favorites,返回的每个模型都会有 .content_object 存在,它将是 Blog 的实例...

{% for fav in favorites %}
    {# This would print the blog title for every favorite #} 
    {{ fav.content_object.title }}<br/>
{% endfor %}

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 %}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文