Search code examples
jsondjangotypesmetadata

How can I change the returned field metadata type in the json returned by OPTIONS using the Django REST Framework?


I am currently writing an automated script to extract metadata types from my models in Django endpoints which I am trying to hook up to swift.

How to pass information about the field data type to the frontend when using Django Rest Framework?

The previous question on stack exchange explains how the OPTIONS field can be used to extract the metadata from my models; however, I run into a problem in that not all fields returned are detailed. Particularly, foreign key fields do not specify the correct metadata type.

for instance,

"created_by_merchant": {
"type": "field",
"required": false,
"read_only": true,
"label": "Created by merchant"
}

"item_size_selection": {
"type": "field",
"required": false,
"read_only": false,
"label": "Item size selection"
}

Both are foreign keys. Created by merchant should be an integer, item_size_selection should be a charfield. Is there any way I can specify the type for particular fields in my OPTIONS?


Solution

  • Found a work around to the issue. Within serializers, one can specify foreign keys as their particular serializer field using source.

    Here is an example:

    created_by_merchant = serializers.IntegerField(source='created_by_merchant_id', read_only=True)
    

    Not sure why I needed to add the read_only field again even though its specified in the meta class, but it requires matching there for it to work with read only.