Search code examples
pythondjangorestforeign-keysdjango-rest-framework

drop down foreign key selection in Django Rest Framework


Bar has ForeignKey to Foo, many Bar to one Foo. Using Forms in Django, a foreign key defaults to a select list input.

I would like this functionality in Django Rest Framework, first for Browsable API, then for Template HTML Renderer. I've been over nested relations in the docs and also have seen this related question, but it isn't making sense. At least it does make me think, I should be seeing the drop down behavior just like stock Django Forms.

ultimately I want a way to let us select an existing Foo when creating/updating Bar I believe I could do it with TemplateHTMLRenderer by hand crafting a form that changes form fields to the full JSON data, i.e. a new Bar that is pointing to the existing Foo, assuming I write update and create methods on Bar. But this sounds to me like I'm missing the "easy way" somewhere.

class BarSerializer(serializers.ModelSerializer):

    # This shows Foo.foo within serialzied Bar JSON:
    # I suspect I am missing something with the relation that would allow me to select foo from a list
    foo = serializers.SlugRelatedField(many=False, read_only=True,slug_field="foo")


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

    
class FooSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')

    # This shows the Bar serialized within the Foo JSON i.e. nested serialization
    bars =  BarSerializer(many=True);

    # reverse rel: related_name='bars' in Foo model
    class Meta:
        model = Foo
        # 'bars' is the related name pointing from bar to foo
        fields = ('bars', 'foo', 'owner')  

I understand that to save nested data, my serializer needs update and create. Implementing this now. But I can't get my head around, what would I do to have DRF populate a select input with some representation of the Foo options?


Solution

  • This was five months ago so you probably have the answer by now but my google search brought me to here to start off with.

    So incase you or others happen to come by here the answer that I found worked best was:

    Django admin foreign key dropdown with custom value

    Basically you need to tell it in one of two ways which field/fields to use as the string for the drop down.