Dropdown foreign key selection in Django Rest Framework

The bar has ForeignKey for Foo, many bars for one Foo. Using forms in Django, the default is to enter a selection list by default .

I need this functionality in the Django Rest Framework, first for the API browser, and then for the HTML Renderer template. I was over nested relationships in documents , and also saw this related question , but that doesn't make sense. At the very least, it makes me think that I should see a drop down, just like the stock Django Forms.

Ultimately, I want us to be able to select an existing Foo when creating / updating Bar . I believe that I can do this with TemplateHTMLRenderer by manually creating a form that changes the form fields to full JSON data, i.e. a new bar that points to an existing Foo, suggesting that I am writing an update and creating methods in Bar. But it sounds to me like I'm missing the β€œeasy way”.

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 ie 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 in order to save the embedded data, my serializer needs to be updated and created. We are implementing it now. But I can’t lower my head, what would I do for DRF to fill the selected input with some representation of the Foo parameters?

I'm missing something obvious, huh? Here come the RTFM (again) downvotes: /

+5
source share
1 answer

That was five months ago, so you probably have an answer, but my google search brought me here to start with.

So, if you or other people came here, then the answer I found the best was:

Django foreign key dropdown with custom value

Basically you need to specify this in one of two ways that the field / fields should be used as a string for the drop down list.

+1
source

All Articles