Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In Django admin, one can set up a raw_id_fields in order to have a search widget instead of a select box. This is very neat to spare up a lot of database queries when the foreign key table is huge.

What is the equivalent in the Django Rest Framework browsable views?

like image 397
Benjamin Toueg Avatar asked Sep 04 '13 07:09

Benjamin Toueg


1 Answers

Django Rest Framework 3 no longer supports widget attribute on serializer field. But to get your browsable API even usable, try changing style attribute to use 'base_template': 'input.html' as in 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')

This way your huge select tag with thousands foreign key options will change to simple text input. For more info check docs at http://www.django-rest-framework.org/topics/browsable-api/#handling-choicefield-with-large-numbers-of-items

like image 181
pista329 Avatar answered Oct 01 '22 18:10

pista329