How to set up raw_id_fields in django-rest-framework?

In Django admin, you can configure raw_id_fields to have a search widget instead of a select field. This is very neat to save a lot of database queries when the foreign key table is huge.

What is the equivalent in viewed Django Rest Framework views?

+6
source share
3 answers

Django Rest Framework 3 no longer supports the widget attribute in the serializer field. But to get an accessible API for viewing, try changing the style attribute to use 'base_template': 'input.html' , as shown in the following example:

 class CustomerAddressSerializer(serializers.ModelSerializer): customer = serializers.IntegerField(source='customer_id' style={'base_template': 'input.html', 'placeholder': "Customer ID"}) class Meta: model = models.CustomerAddress fields = ('id', 'customer', 'street', 'zip', 'city') 

Thus, your huge select tag with thousands of options foreign keys will change to plain text input . For more information, check out the docs at http://www.django-rest-framework.org/topics/browsable-api/#handling-choicefield-with-large-numbers-of-items

+5
source

Nothing is currently supported. I am pretty sure that requests for applications will be welcome.

+1
source

Conquering what Carlton says, although it would be advisable to discuss on the ticket before he hits the implementation.

Alternatively, you can take a look at using an autocomplete widget ...

http://www.django-rest-framework.org/topics/browsable-api/#autocomplete

0
source

Source: https://habr.com/ru/post/953133/


All Articles