1

I am writing a Django application where a User can save "Search".

class Searches(models.Model):
        user = models.ForeignKey(User)
        ....

       def get_searches(self):
           try:
                search_list=Searches.objects.get(user)
           except:
                 return []
           else:
               return search_list.

Hence when a User is logged in, in my view,

@login_required
def display_search_list(request):
     user=request.user
     search_list=user.get_searches()
     return render(request,"display.html",{'obj_list':search_list})

My question is about get_searches(self) method I defined above. how can I pass the "currently logged-in User" to get the search_list. All I am interested in is user.get_searches() should return all the saved searches for that User. how to get this working?

Thanks

brain storm
  • 30,124
  • 69
  • 225
  • 393

2 Answers2

5

You have a ForeignKey to the User model in Searches. So you already have a backreference from any user object to all the searches related to that user in this model. For the logged in user, you can call request.user.searches_set.all() and it'll return all the saved searches for the logged in user. Not sure why you wrote that method. Read more at docs.

Bibhas Debnath
  • 14,559
  • 17
  • 68
  • 96
1

Try:

@login_required
def display_search_list(request):
    user=request.user
    search_list=Searches.objects.filter(user_id=user.id)
    return render(request,"display.html",{'obj_list':search_list})

If you need to have a method inside the Searches class, I think your signature should be:

def get_searches(self, id):

But you would need to create an object to call it. I would just build the list in the view.

It does break MVC a little. :) I believe using the get() method is for getting one row, to get more than one you should use filter()

Tony
  • 801
  • 1
  • 7
  • 22
  • Thanks, I will see how it works now. I have another question that is posted here, can you help here: http://stackoverflow.com/questions/22720984/how-to-attach-multiple-modeladmins-to-useradmin-in-django – brain storm Mar 28 '14 at 19:37
  • This is really unnecessary. Django has model back-references just for this. – Bibhas Debnath Mar 29 '14 at 07:03