-
-
Notifications
You must be signed in to change notification settings - Fork 7k
Problems when Serializing instance of a derived class that is also the target of a OneToOneField #4290
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Previously could fail when serializing a model that: 1. was derived (subclassed) from a model 2. was itself referenced via a one-to-one relationship by a third model 3. had a serializer that listed the referring model in its Meta.fields Now we recursively check up inheritance chain for the referenced field
Exhibits the problem that occurs when a model has a one-to-one relationship with another model that is itself derived (subclassed) from a third model.
Current coverage is 91.15%@@ master #4290 diff @@
==========================================
Files 52 52
Lines 5776 5791 +15
Methods 0 0
Messages 0 0
Branches 0 0
==========================================
+ Hits 5267 5279 +12
- Misses 509 512 +3
Partials 0 0
|
I wonder if we could get the same result by calling Django API. Surely other projects will run into that one and we should consider pushing that to Django |
I looked into that. In the scenario described, the value stored in the table with the one-to-one field really is the value of the ptr to the parent table so the "to_field" variable really is correct when it refers to that field name even though it is not on the original table. |
field_kwargs['slug_field'] = to_field | ||
field_class = self.serializer_related_to_field | ||
if to_field: | ||
def get_related_field(related_model, to_field): |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Haven't looked into the issue in any depth, but we'd certainly want to factor this out. Eg have it as a function somewhere in rest_framework.utils
I have found that when attempting to serialize an instance of a model that:
A FieldDoesNotExist exception would be thrown indicating that the model with the OneToOne field has no field named _ptr where parent is the lower-cased name of the model at the top of the inheritance chain.
The attached pull request searches the inheritance chain recursively to find the correct field.
A unit test has also been included. My fork includes a branch called "foreign-key-to-derived-model-tests' which includes only the unit test. It may be used to verify the problem this pull request resolves.