Django REST - 元数据中的ForeignKey相关模型的URL(OPTIONS)

时间:2018-05-28 09:46:05

标签: python django django-rest-framework

我正在寻找如何在元数据(OPTIONS)中获取ForeignKey相关模型的URL。

型号:

Class Country(models.Model):
    pass

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

我希望下面的“choices_url”可以在OPTIONS上显示:

城市的API(选项)

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

感谢。

1 个答案:

答案 0 :(得分:0)

我检查过,它反转了“view_name”中的URL,字段的view_name是“{basename} -detail”。使用以下类覆盖SimpleMetadata,并在settings.py中设置为默认元数据类。问题已经解决了。 “choices_url”显示在list_view网址上。

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

<强> {项目} /settings.py

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

感谢。