1👍
✅
To return the correct data format the function “to_internal” can be overridden in the ProjectSerializer, like this:
class ProjectSerializer(serializers.HyperlinkedModelSerializer):
seqrecords = ProjectMetaSerializer(source='projectmeta_set', many=True)
class Meta:
model = Project
fields = ['id', 'name', 'seqrecords']
ReadOnlyField = ['id']
def to_internal_value(self, data):
''' Override standard method so validated data have seqrecords '''
context = super(ProjectSerializer, self).to_internal_value(data)
context['seqrecords'] = data['seqrecords']
return context
def validate(self, data):
...
def create(self, validated_data):
...
return project
This method is of course dependent on good a validation function for the “seqrecords” field in validate().
0👍
As you see in the ProjectMetaSerializer
, the fields id
and name
are ReadOnlyFields. So you can’t use them in post
request.
class ProjectMetaSerializer(serializers.ModelSerializer):
seqrecords = SeqRecordSerializer(many=True)
class Meta:
model = ProjectMeta
fields = ['seqrecords',]
class ProjectSerializer(serializers.ModelSerializer):
project_meta = ProjectMetaSerializer(many=True)
class Meta:
model = Project
fields = ['id', 'name', 'project_meta']
ReadOnlyField = ['id']
def create(self, validated_data):
project = Project(name=validated_data['name'])
project.save()
# This is where it all fails
for seq in validated_data['seqrecords']:
sequence = SeqRecord.objects.filter(id=seq['id'])
meta = ProjectMeta(project=project,
sequence=sequence,
order=seq['order'])
meta.save()
return project
class SeqRecordSerializer(serializers.ModelSerializer):
class Meta:
model = SeqRecord
fields = ['id', 'name', 'sequence']
Source:stackexchange.com