[英]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.