Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django filter foreignkey field

Short version:

I have a Django app used for recipes, and want to filter data to be sent to a template in my view. I basically want all recepies that are added by a specific user to be sent as context. The following filtering returns an error message invalid literal for int() with base 10: my_username.

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

The variable uname is passed from a template. On the other hand, filtering on request.user works fine, but is not what I want.

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

Details:

My models are given (relevant fields) as:

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

Where User is an existing Django user. When I call {{ recipe.added_by }} in my template, I get the username as wanted. This username is passed on to a view with href="/profile/{{recipe.added_by}}", where the view looks like the following:

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)

Not sure what I am missing, but from what I can tell, it seems to have something to do with the fact that added_by has a Foreign Key to a User. I also tried to change the filter argument to recipe__added_by__added_by = uname according to [1], but Django then returned an error saying "Cannot resolve keyword 'recipe' into field", which seems obvious. My url is:

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

Thanks for any reply. Sorry if this should have been obvious.

[1] Django models filter by foreignkey

like image 401
kennha Avatar asked Jan 10 '23 07:01

kennha


2 Answers

You can try like:

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

And request.user works fine for Recipe.objects.filter(added_by = request.user) because request.user is an object. details: https://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships

like image 90
ruddra Avatar answered Jan 15 '23 18:01

ruddra


When child class defined as

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

makemigration generates foreign key as added_by_id. So, you have to use corresponding field name in filter.

Eg: recipes = Recipe.objects.filter(added_by_id = uname)

like image 33
Ramesh Seera Avatar answered Jan 15 '23 20:01

Ramesh Seera