예제 #1
0
    def get_expand_id_list_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)
        """
        method_field_name = 'get_{0}_id_only'.format(field_name)

        # A SerializerMethodField can be used for custom ID generation
        if hasattr(self, method_field_name):
            return serializers.SerializerMethodField(
                method_name=method_field_name, source='*')

        if not field_definition.get('many'):
            raise ValueError("Can only expand as ID-only on *-to-many fields")

        kwargs = dict(many=True, read_only=True)

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

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

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

        return serializers.PrimaryKeyRelatedField(**kwargs)
 def test_representation_explicit_invalid_model_reference(self):
     with self.assertRaisesRegex(AssertionError, "not a Django model"):
         (
             fields.HashIdField(
                 model="tests.base.TEST_HASH_IDS"
             ).to_representation(self.car_model.pk)
         )
예제 #3
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)
 def test_internal_value_hash_id_validation(self):
     with self.assertRaisesRegex(ValidationError, "not a valid HashId"):
         (
             fields.HashIdField(
                 model="tests.models.CarModel"
             ).to_internal_value("abc123")
         )
 def test_internal_value_explicit_invalid_model_reference(self):
     with self.assertRaisesRegex(AssertionError, "not a Django model"):
         (
             fields.HashIdField(
                 model="tests.base.TEST_HASH_IDS"
             ).to_internal_value(self.external_id(self.car_model))
         )
class CarModelTestSerializer(ModelSerializer):
    """
    A basic ModelSerializer using a HashIdField.
    """
    id = fields.HashIdField()

    class Meta:
        model = models.CarModel
        fields = ('id', 'name')
class CarModelMethodTestSerializer(ModelSerializer):
    """
    A ModelSerializer using a method to retrieve the model for a HashIdField.
    """
    manufacturer_id = fields.HashIdField()

    class Meta:
        model = models.CarModel
        fields = ('id', 'name', 'manufacturer_id')

    def get_manufacturer_id_model(self):
        return models.Manufacturer
 def test_internal_value_requires_model(self):
     with self.assertRaisesRegex(AssertionError, 'No "model"'):
         fields.HashIdField().to_internal_value(
             self.external_id(self.car_model))
 def test_representation_explicit_model_reference(self):
     representation = (fields.HashIdField(
         model='tests.models.CarModel').to_representation(
             self.car_model.pk))
     self.assertEqual(self.external_id(self.car_model), representation)
 def test_representation_explicit_model_object(self):
     representation = (fields.HashIdField(
         model=models.CarModel).to_representation(self.car_model.pk))
     self.assertEqual(self.external_id(self.car_model), representation)
 def test_representation_requires_model(self):
     with self.assertRaisesRegex(AssertionError, 'No "model"'):
         fields.HashIdField().to_representation(self.car_model.pk)
 def test_internal_value_hash_id_validation(self):
     with self.assertRaisesRegex(ValidationError, 'not a valid HashId'):
         (fields.HashIdField(
             model='tests.models.CarModel').to_internal_value('abc123'))
 def test_internal_value_explicit_model_reference(self):
     internal_value = (fields.HashIdField(
         model='tests.models.CarModel').to_internal_value(
             self.external_id(self.car_model)))
     self.assertEqual(self.car_model.pk, internal_value)
 def test_internal_value_explicit_model_object(self):
     internal_value = (fields.HashIdField(
         model=models.CarModel).to_internal_value(
             self.external_id(self.car_model)))
     self.assertEqual(self.car_model.pk, internal_value)