Django 1.11, Django Rest Framework 3.6.
I have 2 models, Foo and Bar:
class Foo(models.Model):
name=models.CharField()
sex=models.CharField()
class Bar(models.Model):
type=models.CharField()
foo=models.ForeignKey(Foo)
In my serializers.py I have:
class FooSerializer(serializers.ModelSerializer):
class Meta:
model = Foo
fields = ('sex',)
class BarSerializer(serializers.ModelSerializer):
foo = FooSerializer(many=False)
class Meta:
model = Bar
fields = ('type', 'foo',)
This produces JSON like this:
{
"type": "abcdefg",
"foo": {
"sex": "male"
}
}
What I really want is for the "foo" field to be flat, i.e.:
{
"type": "abcdefg",
"foo": "male"
}
One possible solution would be to use the StringRelatedField, but this would entail setting the __str__ method of the Foo model to return the sex field, which I do not want.