Answer the question
In order to leave comments, you need to log in
How to pass a POST object as a request to Serializer relations DRF?
On a Vue client on a Django Rest FrameWork server.
# models.py
class UnitMeasure(models.Model):
name = models.CharField(max_length=128, verbose_name='Ед. изм.')
is_archive = models.BooleanField(verbose_name='В архиве', default=False)
class Material(models.Model):
name = models.CharField(max_length=200, verbose_name=u'Название материала')
unit_measure = models.ForeignKey(UnitMeasure, null=True, blank=True, verbose_name='Ед. изм.')
#serializers.py
class UnitMeasureSerializer(serializers.ModelSerializer):
class Meta:
model = UnitMeasure
fields = ('__all__')
class MaterialSerializer(serializers.ModelSerializer):
unit_measure = UnitMeasureSerializer()
class Meta:
model = Material
fields = ('id', 'name', 'unit_measure')
def create(self, validated_data):
un_m = validated_data.pop('unit_measure')
material = Material.objects.create(**validated_data, unit_measure_id=un_m.id)
return material
{
"name": "Бетон В30",
"unit_measure": {
"id": 1,
"name": "м3"
}
}
Answer the question
In order to leave comments, you need to log in
You can try to do this:
1) Specify the __str__ method for UnitMeasure
def __str__(self):
return self.name
class CustomPrimaryKeyRelatedField(PrimaryKeyRelatedField):
def to_representation(self, value):
return {'id': value.pk, 'name': str(value)}
def to_internal_value(self, data):
if isinstance(data, dict):
data = data.get('id')
return super(CustomPrimaryKeyRelatedField, self).to_internal_value(data)
class MaterialSerializer(serializers.ModelSerializer):
unit_measure = CustomPrimaryKeyRelatedField()
class Meta:
model = Material
fields = ('id', 'name', 'unit_measure')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question