Django REST - 元数据中外键相关模型的URL(选项)



我正在寻找如何在元数据中获取外键相关模型的网址(选项(。

模型:

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

我希望下面的"choices_url"可以显示在选项上:

城市的 API(选项(

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

谢谢。

我检查了一下,它从"view_name"反转为URL,并且该字段的view_name是"{basename}-detail"。使用以下类重写简单元数据,并在 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'
}

谢谢。

相关内容

  • 没有找到相关文章

最新更新