def test_output(self): field = ComboReferenceField(serializer=ReferencedSerializer) instance = ReferencedDoc.objects.create(name="foo") strid = str(instance.id) ref = instance.to_dbref() assert field.to_representation(instance) == strid assert field.to_representation(ref) == strid
class TestSerializer(DocumentSerializer): class Meta: model = ReferencingDoc fields = '__all__' depth = 1 ref = ComboReferenceField(serializer=ReferencedSerializer)
class ComboReferencingSerializer(DocumentSerializer): class Meta: model = ReferencingDoc fields = '__all__' ref = ComboReferenceField(serializer=ReferencedSerializer) def save_subdocs(self, validated_data): doc = validated_data['ref'] if isinstance(doc, Document): doc.save() def create(self, validated_data): self.save_subdocs(validated_data) return super(ComboReferencingSerializer, self).create(validated_data) def update(self, instance, validated_data): self.save_subdocs(validated_data) return super(ComboReferencingSerializer, self).update(instance, validated_data)
def test_input_data(self): field = ComboReferenceField(serializer=ReferencedSerializer) value = field.to_internal_value({'name': "Foo"}) assert isinstance(value, ReferencedDoc) assert value.name == "Foo" assert value.id is None
def test_input_ref(self): field = ComboReferenceField(serializer=ReferencedSerializer) instance = ReferencedDoc.objects.create(name="foo") ref = instance.to_dbref() assert field.to_internal_value(str(instance.id)) == ref assert field.to_internal_value({'_id': str(instance.id)}) == ref