Model Method with a Variable
I have the following view that takes the value of "q" from a template:
from django.http import HttpResponse
from django.shortcuts import render_to_response
from GOTHAMWEB.GRID.models import *
def search(request):
errors = []
if 'q' in request.GET:
q = request.GET['q']
if not q:
errors.append('Enter a search term.')
elif len(q) > 20:
errors.append('Please enter at most 20 characters.')
else:
srvr = Server.objects.filter(name__icontains=q)
return render_to_response('search_results.html',
{'srvr': srvr, 'query': q})
return render_to_response('search_form.html',
{'errors': errors})
Is it possible to pass the value o开发者_JAVA技巧f q from the view to a model method, such as "server='q' " below. I have tried this but is fails. Before concluding it cannot be done, will someone please tell me for certain.
class MemoryManager(models.Manager):
def get_query_set(self):
return super(MemoryManager, self).get_query_set().filter(server='q')
It's not at all clear what you are trying to do here. In the function, you are filtering on the value of the GET variable q
. But in the Manager, you are filtering on the string "q"
.
Did you just want to pass the value of q
into the Manager? If so, the easiest way would be to define a separate Manager method:
class MemoryManager(models.Manager):
def filter_server(q):
return self.get_query_set().filter(server=q)
Now you can call Server.memsinserver.filter_server(q)
. Is that what you wanted?
精彩评论