简体   繁体   English

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

[英]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). 我正在寻找如何在元数据(OPTIONS)中获取与ForeignKey相关的模型的URL。

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: 希望下面的“ choices_url”可以显示在OPTIONS上:

City's API (OPTIONS) 城市的API(选项)

"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". 我检查了一下,它从“ view_name”反向指向一个URL,并且该字段的view_name是“ {basename} -detail”。 Override the SimpleMetadata with the following class and set to default metadata class in settings.py. 使用以下类覆盖SimpleMetadata,并在settings.py中将其设置为默认元数据类。 The problem has been solved. 问题已经解决。 The "choices_url" is displayed the list_view url. “ choices_url”显示为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 {Project} /settings.py

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

Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Django中删除ForeignKey时发出有关模型的信号 - Signaling on related model when deleting ForeignKey in django 与Django中的抽象模型相关的ForeignKey字段 - ForeignKey field related to abstract model in Django Django删除另一个模型中没有更多相关外键项的模型实例? - Django deleting a model instance with no more related ForeignKey items in another model? Django rest 相关 model 不包括在内 - Django rest related model not included 如何在Django模型ForeignKey和OneToOneField中获取所有相关对象 - How to get all related objects in django model ForeignKey and OneToOneField Django OneToOneField &amp; Foreignkey - 如何从相关模型中获取价值? - Django OneToOneField & Foreignkey - How to get value from related model? 在Django中获取与此模型相关的所有模型(通过ForeignKey,ManyToMany) - Get all models related to this model in django (via ForeignKey, ManyToMany) 如何在Django的同一模型中获取与ForeignKey相关的主键(pk)? - How to get the foreignKey related primary key (pk) in the same model in django? 内联编辑与模型相关的所有ForeignKey [django admin] - inline edit all ForeignKey related to a model[django admin] Select 仅与 Django 中的另一个 model 相关的选项 - Select only the options that are related to another model in Django
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM