umutbozkurt/django-rest-framework-mongoengine

Index makes _cls field required

Vayel opened this issue · 3 comments

Vayel commented
class Parent(Document):
    name = fields.StringField(required=True)
    
    meta = {
        'indexes': [
            {
                'fields': ['name'],
                'unique': True,
            },
        ],
        'allow_inheritance': True,
    }

class Child(Parent): pass

class ChildSerializer(DocumentSerializer):
    class Meta:
        model = Child
        fields = '__all__'
        read_only_fields = ['_cls',]

The serializer has a UniqueTogetherValidator on (name, _cls) which makes the field _cls required even if it is read-only. I remedied to that by adding a default value to the field:

class ChildSerializer(DocumentSerializer):
    class Meta:
        model = Child
        fields = '__all__'
        read_only_fields = ['_cls',]
        extra_kwargs = {
            '_cls': {'default': 'Parent.Child'}
        }

I think this default value should be added by DRF-ME.

Vayel commented

This is the solution recommended by DRF:

http://www.django-rest-framework.org/api-guide/serializers/#specifying-read-only-fields

Note: There is a special-case where a read-only field is part of a unique_together constraint at the model level. In this case the field is required by the serializer class in order to validate the constraint, but should also not be editable by the user.

The right way to deal with this is to specify the field explicitly on the serializer, providing both the read_only=True and default=… keyword arguments.

Vayel commented

@BurkovBA do you think we should add this default value in DRF-ME or is it up to the user?

@Vayel

Hi, Vincent, sorry for late response.

I think, if DRF leaves it up to the user, we should leave it up to the user as well. This will be consistent with DRF, right?

May be, we could mention this in the documentation somewhere, though.

Sigh, I still can't find time for the release. Sorry about that.