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