0

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.

2 Answers 2

1

An easier alternative is to use SlugRelatedField, which can be pointed at any field.

class BarSerializer(serializers.ModelSerializer):
    foo = SlugRelatedField(slug_field='sex')
    class Meta:
        model = Bar
        fields = ('type', 'foo',)
Sign up to request clarification or add additional context in comments.

1 Comment

Easier, but a bit misleading perhaps?
0

you can try SerializerMethodField instead of.

class BarSerializer(serializers.ModelSerializer):
    foo = serializers.SerializerMethodField()

    @staticmethod
    def get_foo(item):
        if item.foo:
           return item.foo.sex

    class Meta:
        model = Bar
        fields = ('type', 'foo',)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.