I have this dummy model
from django.db import models
class ChertModel(models.Model):
username = models.CharField(gettext_lazy('username'), max_length=150, unique=True)
o2 = models.CharField(gettext_lazy('username2'), max_length=150,editable=False, default='lllss')
and with serializer
class ChertSer(serializers.ModelSerializer):
class Meta:
model = ChertModel
fields = ['username','o2']
note I have an instance with username='sd'
and o2='434as'
so when in the view I want to update the o2
fields which is supposedly editable=False
it doesnt update it which is ok but the problem is that it doesnt raise exception over model constraints.
note I have checked this configuration with editable=True
and the serializer applies changes thus there is no problem with serializer.
class ChertView(views.APIView):
def get(self, request):
lt1=ChertModel.objects.get(username='sd')
print('1',lt1.o2)
ser=ChertSer(instance=lt1, data={'username':'sd','o2':'newo2'}, partial=True)
print(ser.is_valid())
ser.is_valid(raise_exception=True)
ser.save()
lt1=ChertModel.objects.get(username='sd')
print('2',lt1.o2)
since it shows the serializer.is_valid True
and wont raise exception would make problem of changes of user not applied to model instance without acknowledging it to user.
so my question is how to detect the times the updating object is not applied due to model constraints?
of course I can manually detect it by checking ser.data=={'username':'sd','o2':'newo2'}
but ser.data
is only can be achieved after saving the instance and not before it. besides this way doesnt specify the constraint which is not applied. the equivalent is to manually check for all attributes which is not agreeable when we are using a framework.
so is there any more formal or common way to automatically detect constraints not being applied before saving the instance?
CodePudding user response:
The validation on perticuler field is skipped by default, what you can do is overwrite the validation
function in serializer and raise exception from their.
CodePudding user response:
When editable=False
is specified. The field won't be shown in admin or any other ModelForms, they are also skipped during validation.
You can specify read_only_fields
at the serializer level.
class ChertSer(serializers.ModelSerializer):
class Meta:
model = ChertModel
fields = ['username','o2']
read_only_fields = ('o2',)
If there are multiple serializers for this model and you dont want to dupilicate adding these. You can define read only fields at an AbstractSerializer and inherit it over serializer.