def get_model(self):
        """
        Return the model to generate the HashId for.

        By default, this will equal the model defined within the Meta of the
        ModelSerializer, but can be redefined either during initialisation
        of the Field, or by providing a get_<field_name>_model method on the
        parent serializer.

        The Meta can either explicitly define a model, or provide a
        dot-delimited string path to it.
        """
        if self.model is None:
            custom_fn_name = 'get_{0}_model'.format(self.field_name)

            if hasattr(self.parent, custom_fn_name):
                return getattr(self.parent, custom_fn_name)()
            else:
                try:
                    return self.parent.Meta.model
                except AttributeError:
                    raise AssertionError(
                        'No "model" value passed to field "{0}"'
                        .format(type(self).__name__)
                    )
        elif isinstance(self.model, six.string_types):
            return utils.model_from_definition(self.model)
        else:
            return self.model
Esempio n. 2
0
    def get_expand_id_field(self, field_name, field_definition):
        """
        Return the Serializer Field instance to represent the ID.

        Arguments:
            field_name (str)
            field_definition (dict)

        Returns:
            (rest_framework.fields.Field)
        """
        if hasattr(self, 'get_{0}_id'.format(field_name)):
            return serializers.SerializerMethodField(source='*')

        kwargs = dict(read_only=field_definition['read_only'])

        if 'id_source' in field_definition:
            kwargs.update(source=field_definition['id_source'])

        if utils.get_setting('USE_HASH_IDS', False):
            kwargs.update(pk_field=(custom_fields.HashIdField(
                model=field_definition['id_model'])))

        # If the field is to be writable, PrimaryKeyRelatedField needs a
        # queryset from which to find instances
        if not field_definition['read_only']:
            kwargs['queryset'] = (utils.model_from_definition(
                field_definition['id_model']).objects.all())

        return serializers.PrimaryKeyRelatedField(**kwargs)
Esempio n. 3
0
 def test_pass_string_as_model_definition(self):
     """
     Passing string corresponding to model should import and return model.
     """
     self.assertEqual(models.CarModel,
                      utils.model_from_definition('tests.models.CarModel'))
Esempio n. 4
0
 def test_pass_model_class_as_model_definition(self):
     """
     Test that the method returns its argument when Django model is passed.
     """
     self.assertEqual(models.CarModel,
                      utils.model_from_definition(models.CarModel))
Esempio n. 5
0
 def test_pass_non_model_class_raises_assertion_error(self):
     """
     An error should be raised when a non-Django model class is passed.
     """
     with six.assertRaisesRegex(self, AssertionError, 'not a Django model'):
         utils.model_from_definition(dict)