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
classChildModel(models.Model):
name=models.CharField()
classParentModel(models.Model):
child=models.OneToOneField(ChildModel, on_delete=models.CASCADE)
classParentSerializer(WritableNestedModelSerializer):
classMeta:
fields= ['child']
model=ParentModelclassChildSerializer(serializers.ModelSerializer):
classMeta:
fields= ['name']
model=ChildModelchild=ChildModel.objects.create(name='fu')
parent=ParentModel.objects.create(child=child)
old_child_pk=child.pkparent_serializer=ParentSerializer(data={'pk': parent.pk, 'child': {'name': 'bar'}})
parent_serializer.is_valid(raise_exception=True)
parent=parent_serializer.save()
# What I'd like:# Child serializer went through update()assertparent.child.pk==old_child_pkassertChildModel.objects.count() ==1# What I get:# Child serializer went through create()assertparent.child.pk!=old_child_pkassertChildModel.objects.count() ==2# I got one orphaned
What is the recommended way to achieve what I want ?
I believe this behavior is expectable as long as you have a composition relation, which can also be the case with ForeignKey. In other words, my behavior may be expected when ChildModel has no independent existence from ParentModel.
For esthetic/practical reason I do not want to provide the pk of child model (can be inferred by code).
Current workaround I found is overriding ParentModel ; but this is unclean.
# Override of private method, uh-ohdef_get_related_pk(self, data, model_class):
ifmodel_class==ChildModelandself.instanceandself.instance.child:
# Reuse existing related instance instead of recreating one on each updatereturnself.instance.child.pkelse:
returnsuper()._get_related_pk(data, model_class)
Any thoughts ? I'm wondering if the library could not offer a way to do that.
The text was updated successfully, but these errors were encountered:
Here is minimal fictive example to explain:
What is the recommended way to achieve what I want ?
I believe this behavior is expectable as long as you have a composition relation, which can also be the case with ForeignKey. In other words, my behavior may be expected when
ChildModel
has no independent existence fromParentModel
.For esthetic/practical reason I do not want to provide the pk of child model (can be inferred by code).
Current workaround I found is overriding ParentModel ; but this is unclean.
Any thoughts ? I'm wondering if the library could not offer a way to do that.
The text was updated successfully, but these errors were encountered: