Django过滤外键字段

时间:2014-07-03 07:26:46

标签: python django filter foreign-keys

简短版:

我有一个用于配方的Django应用程序,并希望过滤数据以便在我的视图中发送到模板。我基本上希望特定用户添加的所有接收都作为上下文发送。以下过滤返回错误消息 int()的无效文字,基数为10: my_username

recipes = Recipe.objects.filter(added_by = uname)

从模板传递变量 uname 。另一方面,对 request.user 的过滤工作正常,但不是我想要的。

recipes = Recipe.objects.filter(added_by = request.user)

详细信息:

我的模型(相关领域)如下:

class Recipe (models.Model):
    ...
    ...
    added_by = models.ForeignKey(User)

其中用户是现有的Django用户。当我在模板中调用{{recipe.added_by}}时,我会获得所需的用户名。此用户名将传递到包含 href =" / profile / {{recipe.added_by}}" 的视图,其中视图如下所示:

def profile(request, uname):

    print uname #Correct username printed
    print request.user #Logged in user (not relevant, as userprofile should be visible for all)

    recipes = Recipe.objects.filter(added_by = uname) #Does not work. Why?
    #recipes = Recipe.objects.filter(added_by = request.user)

    form = CommentForm(request.POST)

    context = {
        'uname': uname,
        'recipes': recipes,
        'form': form,
    }
    return render(request, '*app_name*/profile.html', context)

不确定我缺少什么,但据我所知,它似乎与 added_by 具有用户外键的事实有关。我还尝试根据[1]将过滤器参数更改为 recipe__added_by__added_by = uname ,但是Django然后返回了一个错误,说“"无法解析关键字' recipe'进入领域",这似乎是显而易见的。我的网址是:

url(r'^profile/([a-zA-Z0-9]+)/$', 'profile', name='*app_name*-profile'),

感谢您的回复。对不起,如果这应该是显而易见的。

[1] Django models filter by foreignkey

2 个答案:

答案 0 :(得分:2)

您可以尝试:

 recipes = Recipe.objects.filter(added_by__username = uname)

request.user适用于Recipe.objects.filter(added_by = request.user),因为request.user是一个对象。详情:https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships

答案 1 :(得分:1)

当子类定义为

class Recipe (models.Model):
    ...
    ...
    added_by = models.ForeignKey(User)

makemigration生成外键为 added_by_id 。 因此,您必须在过滤器中使用相应的字段名称。

例如:recipes = Recipe.objects.filter(added_by_id = uname)