You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
ModelSerializer UniqueTogetherValidator is incompatible with field source #7100
This case is no longer valid?
It was a convenient way to redirect field names.
Reacted by Gertjan Oude Lohuis, Andrew Kh, Matt Fisher, Charanjit Singh, Sergey Buchko, neoCheck, Mikaël Gourlaouen, Ben Fitzhardinge, Kostas Kokkoros, Jacinda Shelly and 2 more
I'm having the same issue. UniqueTogetherValidator.enforce_required_fields assumes the presence of its listed fields in the dict comprehension:
missing_items = {
field_name: self.missing_message
for field_name in self.fields
if serializer.fields[field_name].source not in attrs
}
I can make my failing tests pass by replacing this with:
fields_from_serializer = [
field
for field in serializer.fields.values()
if field.source in self.fields
]
missing_items = {
field.field_name: self.missing_message
for field in fields_from_serializer
if field.source not in attrs
}
# or just
missing_items = {
field.field_name: self.missing_message
for field in serializer.fields.values()
if field.source in self.fields
and field.source not in attrs
}
and similarly, in UniqueTogetherValidator.filter_queryset, replacing
sources = [
serializer.fields[field_name].source
for field_name in self.fields
]
# with:
sources = [
field.source
for field in serializer.fields.values()
if field.source in self.fields
]
I can't be 100% sure the different way of finding the fields doesn't break any assumptions about when the fields should be present.
changed the title [-]Key_error exception on is_valid() method [/-][+]ModelSerializer UniqueTogetherValidator is incompatible with field source[/+]on Jan 13, 2020
Thanks - I'll look into this. This stems from #7086, which fixed a related bug. It looks like those changes in turn broke UniqueTogetherValidators that are generated by ModelSerializers.
For now, a workaround would be to declare the UniqueTogetherValidators directly on your serializer class. Using the example the issue description...
Hi @rpkilby! Your branch does not seem to fix the issue, at least with manually instantiated UniqueTogetherValidators. This is our test case (working well with DRF 3.10.3):
This test fails even with your branch uniquetogether-field-source:
======================================================================
ERROR: test_issue (project.src.app.tests.drf.DRFIssue)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/project/src/app/tests/drf.py", line 39, in test_issue
self.assertTrue(serializer.is_valid())
File "/git/rpkilby/django-rest-framework/rest_framework/serializers.py", line 219, in is_valid
self._validated_data = self.run_validation(self.initial_data)
File "/git/rpkilby/django-rest-framework/rest_framework/serializers.py", line 420, in run_validation
self.run_validators(value)
File "/git/rpkilby/django-rest-framework/rest_framework/serializers.py", line 453, in run_validators
super().run_validators(to_validate)
File "/git/rpkilby/django-rest-framework/rest_framework/fields.py", line 589, in run_validators
validator(value, self)
File "/git/rpkilby/django-rest-framework/rest_framework/validators.py", line 150, in __call__
queryset = self.filter_queryset(attrs, queryset, serializer)
File "/git/rpkilby/django-rest-framework/rest_framework/validators.py", line 121, in filter_queryset
for field_name in self.fields
File "/git/rpkilby/django-rest-framework/rest_framework/validators.py", line 121, in <listcomp>
for field_name in self.fields
File "/git/rpkilby/django-rest-framework/rest_framework/utils/serializer_helpers.py", line 148, in __getitem__
return self.fields[key]
KeyError: 'customer_object_ref'
This issue is breaking a lot of our code base as we have some of those UniqueTogetherValidator pretty much everywhere.
@cepbuch Note that customer_object_ref is a child of the nested serializer customer_info, therefore object_ref does not refer to a field of MySerializer. I can't seem to fix it that way (customer_info.order_ref would be a correct reference but it does not work either).
Hi @lerela. As @cepbuch mentioned, the fields on the UniqueTogetherValidator should correspond to the serializer field names, not the names of the source model fields. From the docs:
fieldsrequired - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class.
Validating fields across a nested serializer was not intended to be supported and only worked due to the previous bug (validator incorrectly checked source model fields instead of serializer fields).
That all said, I'm not entirely sure what to recommend. If possible, it would be best if you could move your nested serializer fields to their parent serializers, but I realize this may not be possible. An alternative would be to recreate the old UniqueTogetherValidator from 3.10 and roll back the change to Serializer._read_only_defaults.
Hi @rpkilby. This is a huge breaking change for us (but I understand that our code base makes use of an old loophole!) and it feels like it should at least be part of the 3.11 announcement (but maybe it'll be in the release notes when they are published).
I'll need more time to assess the impact on our project as we cannot break public APIs and move the fields onto their parent serializers. I assume we'll have either to follow your advice with the old UniqueTogetherValidator or move this logic to the serializers validate method.
Activity
napsterv commentedon Jan 3, 2020
Why aren't your fields in a list?
xordoquy commentedon Jan 3, 2020
@napsterv it's equivalent to a tuple so it's fine anyway.
@hauworkarea could you paste the entire traceback please ?
andrkhr commentedon Jan 3, 2020
@xordoquy that's entire traceback
It seems that the problem occurs when there is a unique_together in the meta class of the model.
Yes, the model contains unique_together.
Corrected the original description.
MattFisher commentedon Jan 6, 2020
I'm having the same issue.
UniqueTogetherValidator.enforce_required_fieldsassumes the presence of its listed fields in the dict comprehension:I can make my failing tests pass by replacing this with:
and similarly, in
UniqueTogetherValidator.filter_queryset, replacingI can't be 100% sure the different way of finding the fields doesn't break any assumptions about when the fields should be present.
harshal-dhumal commentedon Jan 10, 2020
I'm getting the same issue with DRF 3.11
I have unique_together constraint where one field is ForeignKey.
Serializer
Model
[-]Key_error exception on is_valid() method [/-][+]ModelSerializer UniqueTogetherValidator is incompatible with field source[/+]rpkilby commentedon Jan 13, 2020
Thanks - I'll look into this. This stems from #7086, which fixed a related bug. It looks like those changes in turn broke
UniqueTogetherValidators that are generated byModelSerializers.For now, a workaround would be to declare the
UniqueTogetherValidators directly on your serializer class. Using the example the issue description...rpkilby commentedon Jan 15, 2020
Hi all, just opened #7143. If you could test those changes to see if they fix the issue, any feedback would be appreciated.
lerela commentedon Jan 20, 2020
Hi @rpkilby! Your branch does not seem to fix the issue, at least with manually instantiated UniqueTogetherValidators. This is our test case (working well with DRF 3.10.3):
This test fails even with your branch
uniquetogether-field-source:This issue is breaking a lot of our code base as we have some of those UniqueTogetherValidator pretty much everywhere.
cepbuch commentedon Jan 20, 2020
@lerela Seems like you should try use serializer field name (not source model field name) in
UniqueTogetherValidator.i.e. in your case this would probably be like this
Not sure if it'll work in your case, but in my case where I had
=> the following validator in
CandidateSerializermeta solved the issue:lerela commentedon Jan 20, 2020
@cepbuch Note that
customer_object_refis a child of the nested serializercustomer_info, thereforeobject_refdoes not refer to a field ofMySerializer. I can't seem to fix it that way (customer_info.order_refwould be a correct reference but it does not work either).rpkilby commentedon Jan 21, 2020
Hi @lerela. As @cepbuch mentioned, the
fieldson theUniqueTogetherValidatorshould correspond to the serializer field names, not the names of the source model fields. From the docs:Validating fields across a nested serializer was not intended to be supported and only worked due to the previous bug (validator incorrectly checked source model fields instead of serializer fields).
That all said, I'm not entirely sure what to recommend. If possible, it would be best if you could move your nested serializer fields to their parent serializers, but I realize this may not be possible. An alternative would be to recreate the old
UniqueTogetherValidatorfrom 3.10 and roll back the change toSerializer._read_only_defaults.lerela commentedon Jan 22, 2020
Hi @rpkilby. This is a huge breaking change for us (but I understand that our code base makes use of an old loophole!) and it feels like it should at least be part of the 3.11 announcement (but maybe it'll be in the release notes when they are published).
I'll need more time to assess the impact on our project as we cannot break public APIs and move the fields onto their parent serializers. I assume we'll have either to follow your advice with the old
UniqueTogetherValidatoror move this logic to the serializersvalidatemethod.Thanks @rpkilby and @cepbuch for your insights!
lerela commentedon Jan 28, 2020
@rpkilby we observed the initial issue in addition to the undefined behavior I reported and I can confirm that your branch fixes it.
MattFisher commentedon Feb 10, 2020
@rpkilby I can confirm your branch fixes our use case, thanks!
andrkhr commentedon Feb 12, 2020
@rpkilby +1
your branch fixes our problem, thanks!
lane-eb commentedon Apr 30, 2021
@rpkilby +1
Cool.
unique_togetherunchanged.Then the
UniqueTogetherValidatorwill return400 Bad Requestbefore I got theif serializer.fields[field_name].source not in attrskeyError('user').Great. Perfect.