src/hdabo/forms.py
author ymh <ymh.work@gmail.com>
Fri, 20 Mar 2015 01:42:45 +0100
changeset 571 d9642be7c937
parent 266 825ff4d6a8ac
child 660 04255afd160e
permissions -rw-r--r--
replace commit_on_success with atomic
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
11
143ab88d17f8 add ordered manytomany fields and indexing
ymh <ymh.work@gmail.com>
parents:
diff changeset
     1
# -*- coding: utf-8 -*-
143ab88d17f8 add ordered manytomany fields and indexing
ymh <ymh.work@gmail.com>
parents:
diff changeset
     2
from django import forms
143ab88d17f8 add ordered manytomany fields and indexing
ymh <ymh.work@gmail.com>
parents:
diff changeset
     3
from django.db.models.query import QuerySet
143ab88d17f8 add ordered manytomany fields and indexing
ymh <ymh.work@gmail.com>
parents:
diff changeset
     4
143ab88d17f8 add ordered manytomany fields and indexing
ymh <ymh.work@gmail.com>
parents:
diff changeset
     5
143ab88d17f8 add ordered manytomany fields and indexing
ymh <ymh.work@gmail.com>
parents:
diff changeset
     6
class SortedMultipleChoiceField(forms.ModelMultipleChoiceField):
143ab88d17f8 add ordered manytomany fields and indexing
ymh <ymh.work@gmail.com>
parents:
diff changeset
     7
    def clean(self, value):
143ab88d17f8 add ordered manytomany fields and indexing
ymh <ymh.work@gmail.com>
parents:
diff changeset
     8
        queryset = super(SortedMultipleChoiceField, self).clean(value)
143ab88d17f8 add ordered manytomany fields and indexing
ymh <ymh.work@gmail.com>
parents:
diff changeset
     9
        if value is None or not isinstance(queryset, QuerySet):
143ab88d17f8 add ordered manytomany fields and indexing
ymh <ymh.work@gmail.com>
parents:
diff changeset
    10
            return queryset
143ab88d17f8 add ordered manytomany fields and indexing
ymh <ymh.work@gmail.com>
parents:
diff changeset
    11
        object_list = dict((
143ab88d17f8 add ordered manytomany fields and indexing
ymh <ymh.work@gmail.com>
parents:
diff changeset
    12
            (unicode(key), value)
143ab88d17f8 add ordered manytomany fields and indexing
ymh <ymh.work@gmail.com>
parents:
diff changeset
    13
            for key, value in queryset.in_bulk(value).iteritems()))
143ab88d17f8 add ordered manytomany fields and indexing
ymh <ymh.work@gmail.com>
parents:
diff changeset
    14
        return [object_list[unicode(pk)] for pk in value]