Beispiel #1
0
def _merge_fields_and_pk(pk, fields):
    fields_and_pk = OrderedDict()
    fields_and_pk['pk'] = pk
    fields_and_pk[pk.name] = pk
    fields_and_pk.update(fields)

    return fields_and_pk
Beispiel #2
0
def _get_reverse_relationships(opts):
    """
    Returns an `OrderedDict` of field names to `RelationInfo`.
    """
    # Note that we have a hack here to handle internal API differences for
    # this internal API across Django 1.7 -> Django 1.8.
    # See: https://code.djangoproject.com/ticket/24208

    reverse_relations = OrderedDict()
    for relation in opts.get_all_related_objects():
        accessor_name = relation.get_accessor_name()
        related = getattr(relation, 'related_model', relation.model)
        reverse_relations[accessor_name] = RelationInfo(
            model_field=None,
            related=related,
            to_many=relation.field.rel.multiple,
            has_through_model=False)

    # Deal with reverse many-to-many relationships.
    for relation in opts.get_all_related_many_to_many_objects():
        accessor_name = relation.get_accessor_name()
        related = getattr(relation, 'related_model', relation.model)
        reverse_relations[accessor_name] = RelationInfo(
            model_field=None,
            related=related,
            to_many=True,
            has_through_model=(
                (getattr(relation.field.rel, 'through', None) is not None)
                and not relation.field.rel.through._meta.auto_created))

    return reverse_relations
Beispiel #3
0
def _get_fields(opts):
    fields = OrderedDict()
    for field in [
            field for field in opts.fields if field.serialize and not field.rel
    ]:
        fields[field.name] = field

    return fields
Beispiel #4
0
 def choices(self):
     queryset = self.child_relation.queryset
     iterable = queryset.all() if (hasattr(queryset, 'all')) else queryset
     items_and_representations = [
         (item, self.child_relation.to_representation(item))
         for item in iterable
     ]
     return OrderedDict([
         (six.text_type(item_representation),
          six.text_type(item) + ' - ' + six.text_type(item_representation))
         for item, item_representation in items_and_representations
     ])
Beispiel #5
0
    def __init__(self, choices, **kwargs):
        # Allow either single or paired choices style:
        # choices = [1, 2, 3]
        # choices = [(1, 'First'), (2, 'Second'), (3, 'Third')]
        pairs = [
            isinstance(item, (list, tuple)) and len(item) == 2
            for item in choices
        ]
        if all(pairs):
            self.choices = OrderedDict([(key, display_value)
                                        for key, display_value in choices])
        else:
            self.choices = OrderedDict([(item, item) for item in choices])

        # Map the string representation of choices to the underlying value.
        # Allows us to deal with eg. integer choices while supporting either
        # integer or string input, but still get the correct datatype out.
        self.choice_strings_to_values = dict([(six.text_type(key), key)
                                              for key in self.choices.keys()])

        self.allow_blank = kwargs.pop('allow_blank', False)

        super(ChoiceField, self).__init__(**kwargs)
Beispiel #6
0
class ChoiceField(Field):
    default_error_messages = {
        'invalid_choice': _('`{input}` is not a valid choice.')
    }

    def __init__(self, choices, **kwargs):
        # Allow either single or paired choices style:
        # choices = [1, 2, 3]
        # choices = [(1, 'First'), (2, 'Second'), (3, 'Third')]
        pairs = [
            isinstance(item, (list, tuple)) and len(item) == 2
            for item in choices
        ]
        if all(pairs):
            self.choices = OrderedDict([(key, display_value)
                                        for key, display_value in choices])
        else:
            self.choices = OrderedDict([(item, item) for item in choices])

        # Map the string representation of choices to the underlying value.
        # Allows us to deal with eg. integer choices while supporting either
        # integer or string input, but still get the correct datatype out.
        self.choice_strings_to_values = dict([(six.text_type(key), key)
                                              for key in self.choices.keys()])

        self.allow_blank = kwargs.pop('allow_blank', False)

        super(ChoiceField, self).__init__(**kwargs)

    def to_internal_value(self, data):
        if data == '' and self.allow_blank:
            return ''

        try:
            return self.choice_strings_to_values[six.text_type(data)]
        except KeyError:
            self.fail('invalid_choice', input=data)

    def to_representation(self, value):
        if value in ('', None):
            return value
        return self.choice_strings_to_values[six.text_type(value)]
Beispiel #7
0
def _get_forward_relationships(opts):
    """
    Returns an `OrderedDict` of field names to `RelationInfo`.
    """
    forward_relations = OrderedDict()
    for field in [
            field for field in opts.fields if field.serialize and field.rel
    ]:
        forward_relations[field.name] = RelationInfo(model_field=field,
                                                     related=_resolve_model(
                                                         field.rel.to),
                                                     to_many=False,
                                                     has_through_model=False)

    # Deal with forward many-to-many relationships.
    for field in [field for field in opts.many_to_many if field.serialize]:
        forward_relations[field.name] = RelationInfo(
            model_field=field,
            related=_resolve_model(field.rel.to),
            to_many=True,
            has_through_model=(not field.rel.through._meta.auto_created))

    return forward_relations
 def __init__(self, serializer):
     self.serializer = serializer
     self.fields = OrderedDict()
Beispiel #9
0
def _merge_relationships(forward_relations, reverse_relations):
    return OrderedDict(
        list(forward_relations.items()) + list(reverse_relations.items()))
Beispiel #10
0
 def choices(self):
     return OrderedDict([(six.text_type(self.to_representation(item)),
                          six.text_type(item))
                         for item in self.queryset.all()])