简体   繁体   中英

Django REST - URL of ForeignKey related model in metadata(OPTIONS)

I'm looking for how to get the url of ForeignKey related model in metadata(OPTIONS).

Models:

Class Country(models.Model):
    pass

Class City(models.Model):
    country = ForeignKey(Country)

I wish the "choices_url" below can be showed on the OPTIONS:

City's API (OPTIONS)

"actions": {
    "POST": {
        "country": {
            "type": "related",
            "required": true,
            "read_only": false,
            "label": "Country",
            "choices_url": "http://example.com/api/country/"

Thanks.

I checked, it reverse to a URL from the "view_name" and the view_name of the field is "{basename}-detail". Override the SimpleMetadata with the following class and set to default metadata class in settings.py. The problem has been solved. The "choices_url" is displayed the list_view url.

import re


def get_view_name(view_name: str, view_type: str) -> str:
    if view_type in ['list', 'detail']:
        return re.sub('(.*)-[^.]*', f'\\1-{view_type}', view_name)
    raise ValueError(
        f"Wrong view_type. It should be either 'list' or 'detail'. "
        f'<:param view_type>: {view_type}')

class RestMetadata(SimpleMetadata):    
    def get_field_info(self, field):
        field_info = super().get_field_info(field)
        if (not field_info.get('read_only') and
                hasattr(field, 'choices')):
            if isinstance(field, serializers.HyperlinkedRelatedField):
                view_name = get_view_name(field.view_name, 'list')
                field_info['choices_url'] = field.reverse(view_name, request=field.parent.context['request'])
            elif (
                    isinstance(field, serializers.ManyRelatedField)
                    and isinstance(field.child_relation, serializers.ManyRelatedField)):
                field_child = field.child_relation
                view_name = get_view_name(field_child.view_name, 'list')
                field_info['choices_url'] = field_child.reverse(view_name, request=field.parent.context['request'])

        return field_info

{Project}/settings.py

REST_FRAMEWORK = {
    'DEFAULT_METADATA_CLASS': '{Path-of-RestMetadata}.RestMetadata'
}

Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM