django rest framework - DRF 3.0: UniqueTogetherValidator with a read-only field -
in process of upgrading django rest framework 3.0 2.4.4 , want have read-only user field, failing because 'user' being required uniquetogethervalidator (i think)
i have model (excuse typos, simplified , code works fine irl):
class examplemodel(models.model): some_attr = models.positivesmallintegerfield() other_attr = models.positivesmallintegerfield() user = models.foreignkey(user) class meta: unique_together = ('some_attr', 'other_attr', 'user')
viewset:
class exampleviewset(viewsets.modelviewset): queryset = examplemodel.objects.all() serializer_class = exampleserializer def perform_create(self, serializer): serializer.save(user=self.request.user) def perform_update(self, serializer): serializer.save(user=self.request.user)
serializer:
class exampleserializer(serializers.modelserializer): user = userserializer(read_only=true) class meta: model = examplemodel
now, keep getting errors saying: {"user":["this field required."]}
, not case before. in different example same basic problem, assertion error may not set both 'read_only' , 'required'
though not setting user required.
i receive same error regardless if add required=false
user attribute in serializer, or if add user the excluded fields in serializer's meta.
when use handy new serializer printing, see:
class meta: validators = [uniquetogethervalidator(queryset=examplemodel.objects.all(), fields=('user', 'some_attr', 'other_attr'))]
which gets automatically added based on model's unique_together. if explicitly overwrite , not include 'user' in fields uniquetogethervalidator
works before.
is intended consequence of 3.0 update? seems me adding request.user
in perform_create
/ perform_update
standard drf procedure demonstrated in tutorial. realize not having new validation means failing @ db level instead, , new validation gives better error messages, but
is there solution other override validation every serializer issue?
thanks in advance help!
this a known issue in process of addressing within django rest framework. of right now, there note in documentation uniquetogthervalidator says
note:
uniquetogethervalidation
class imposes implicit constraint fields applies treated required. fieldsdefault
values exception supply value when omitted user input.
this explains why seeing error because field required, though explicitly settings read_only=true
. may want currentuserdefault
class, may suit needs while avoiding issue uniquetogethervalidator
.
class exampleserializer(serializers.modelserializer): user = userserializer( read_only=true default=serializers.currentuserdefault() ) class meta: model = examplemodel
this should same thing perform_create
, perform_update
hooks.
Comments
Post a Comment