crucialfelix/django-ajax-selects — pull request #7 by lechup (2012-04-08 17:00:39+00:00)
Title: Query modifiers - more control over objects shared by ajax_selects

Hi!

Want to share with code I've build on Your codebase. What is all about?

class DistrictForm(forms.ModelForm):
parent = AutoCompleteSelectField('district', help_text=District.parent.field.help_text)
city = AutoCompleteSelectField('city', help_text=District.city.field.help_text)

class Meta:
model = District
def __init__(self, * args, ** kwargs):
super(DistrictForm, self).__init__(*args, ** kwargs)
if 'instance' in kwargs:
self.fields['parent'] = AutoCompleteSelectField('district', required=False, help_text=District.parent.field.help_text, query_modifiers={'cities' : self.instance.city.pk, 'exclude': self.instance.pk})

Note the query_modifiers which can be added while defining form, then we have those available in Lookups from request.GET like this:

class DistrictLookup(LookupChannel):
model = District

def get_query(self,q,request):
objs=District.objects.filter((Q(name__icontains=q) | Q(districtalias__name__icontains=q))).distinct()

exclude = []
try:
if 'exclude' in request.GET:
try:
exclude.append(int(request.GET['exclude']))
except:
for e in request.GET['exclude'].split(','):
exclude.append(int(e))
objs = objs.exclude(pk__in=exclude)
except:
raise Http404

cities = []
try:
if 'cities' in request.GET:
try:
cities.append(int(request.GET['cities']))
except:
for c in request.GET['cities'].split(','):
cities.append(int(c))
objs = objs.filter(Q(city__pk__in=cities))
except:
raise Http404

objs=objs.order_by('name')[:20]

return objs

**If You like the idea I can modify also the docs that it would describe 'hack' with working example.**

Again thanks for sharing app!
LP jr