[#2534] Fait du champ "ref" dans EtablissementBase un champ one-to-one
[auf_django_references.git] / auf / django / references / views.py
1 from django.db.models import Q
2 from django.http import HttpResponse
3 from django.utils import simplejson
4
5 from auf.django.references import models as ref
6
7 def autocomplete_etablissements(request):
8 term = request.GET.get('term')
9 exclude_refs = request.GET.get('exclude_refs')
10 include = request.GET.get('include')
11 if term:
12 etablissements = ref.Etablissement.objects.filter(nom__icontains=term)
13 if exclude_refs:
14 q = Q(**{str(exclude_refs): None})
15 if include:
16 q |= Q(id=include)
17 etablissements = etablissements.filter(q)
18 pays = request.GET.get('pays')
19 if pays:
20 etablissements = etablissements.filter(pays=pays)
21 result = [{'id': e.id, 'label': e.nom} for e in etablissements]
22 else:
23 result = [{'id': e.id, 'label': '%s (%s)' % (e.nom, e.pays.nom), 'value': e.nom}
24 for e in etablissements]
25 else:
26 result = None
27 return HttpResponse(simplejson.dumps(result), mimetype='application/json')
28
29 def etablissement_json(request, id):
30 etablissement = ref.Etablissement.objects.get(id=int(id))
31 result = {}
32 for f in etablissement._meta.fields:
33 result[f.name] = getattr(etablissement, f.attname)
34 json = simplejson.dumps(result,
35 default=lambda obj: obj.isoformat if hasattr(obj, 'isoformat') else '')
36 return HttpResponse(json, mimetype='application/json')