Ticket #2265: iterator_choices_try2.patch

File iterator_choices_try2.patch, 2.2 KB (added by Alex Dedul, 9 years ago)
  • django/db/models/fields/__init__.py

     
    77from django.utils.functional import curry
    88from django.utils.text import capfirst
    99from django.utils.translation import gettext, gettext_lazy
     10from django.utils._itertools import tee
    1011import datetime, os, time
    1112
    1213class NOT_PROVIDED:
     
    8081        self.prepopulate_from = prepopulate_from
    8182        self.unique_for_date, self.unique_for_month = unique_for_date, unique_for_month
    8283        self.unique_for_year = unique_for_year
    83         self.choices = choices or []
     84        self._choices = choices or []
    8485        self.radio_admin = radio_admin
    8586        self.help_text = help_text
    8687        self.db_column = db_column
     
    324325    def bind(self, fieldmapping, original, bound_field_class):
    325326        return bound_field_class(self, fieldmapping, original)
    326327
     328    def _get_choices(self):
     329        if hasattr(self._choices, 'next'):
     330            choices, self._choices = tee(self._choices)
     331        else:
     332            choices = self._choices
     333
     334        return choices
     335    choices = property(_get_choices)
     336
    327337class AutoField(Field):
    328338    empty_strings_allowed = False
    329339    def __init__(self, *args, **kwargs):
  • django/utils/_itertools.py

     
     1try:
     2    from itertools import tee
     3except ImportError:
     4    from itertools import count
     5
     6    def tee(iterable, n=2):
     7        """
     8        A little bit modified code for n iterators
     9        from http://www.python.org/doc/2.3.5/lib/itertools-example.html
     10
     11        Return n independent iterators from a single iterable
     12        """
     13        def gen(next, data={}, cnt=[0]):
     14            dpop = data.pop
     15            for i in count():
     16                if i == cnt[0]:
     17                    item = data[i] = next()
     18                    cnt[0] += 1
     19                else:
     20                    item = dpop(i)
     21                yield item
     22        next = iter(iterable).next
     23        return (gen(next) for x in xrange(n))
Back to Top