我需要user-detail
的URL端点为api/email/user@gmail.com
; api/email/user2@gmail.com
,但无效
如果我将url
字段添加到序列化程序类中,则在user-list
页面上,我有例外:Could not resolve URL for hyperlinked relationship using view name "user-email". You may have failed to include the related model in your API, or incorrectly configured the
lookup_field attribute on this field.
那是我的代码:
serializers.py
class EmailSerializer(serializers.ModelSerializer):
"""
Профиль пользователя
"""
class Meta:
model = User
fields = ('url', 'email', )
read_only_fields = ('email', )
extra_kwargs = {
'url': {'view_name': 'user-email', 'lookup_field': 'email'}
}
views.py
class RetrieveModelViewSet(mixins.RetrieveModelMixin,
mixins.ListModelMixin,
viewsets.GenericViewSet):
"""
действия просмотр
"""
pass
class EmailViewSet(RetrieveModelViewSet):
queryset = User.objects.all()
serializer_class = EmailSerializer
lookup_field = 'email'
urls.py
router.register(r'email', views.EmailViewSet, 'email')
我也尝试通过quote_plus
清除电子邮件字段:
serializers.py
from urllib.parse import quote_plus
class EmailSerializer(serializers.ModelSerializer):
"""
Профиль пользователя
"""
email = quote_plus(serializers.EmailField(read_only=True))
class Meta:
model = User
fields = ('url', 'email', )
read_only_fields = ('email', )
extra_kwargs = {
'url': {'view_name': 'user-email', 'lookup_field': 'email'}
}
但是我有错误:
TypeError: quote_from_bytes() expected bytes
答案 0 :(得分:0)
默认为“。”在查找正则表达式(django-rest-framework.org/api-guide/routers)中是不允许的,您应该更改“ lookup_value_regex”字段以允许标点(“。”)字符。默认值为“ [^ /。] +”,因此您需要从“ [^ /] +”中删除标点符号(“。”)。
答案 1 :(得分:0)
同样的问题,我按如下方法处理。
我将使用电子邮件字段进行查找,但是不可能在URL端点中使用它。
由于我API中的json包含良好的URL端点以及相关的电子邮件,因此我查询json以获取URL端点。一种手动关系:
import requests, json, subprocess
REQUEST_URL = 'http://127.0.0.1:8000/users/?format=json'
login = 'DjangoLogin'
password = 'DjangoPassWord'
response = requests.get(REQUEST_URL, auth=(login, password))
json_data = response.text.encode('utf-8', 'ignore')
readable_json = json.loads(json_data)
email_reference = YOUR_EMAIL_FIELD
new_firstname = YOUR_FIRSTNAME_FIELD
new_lastname = YOUR_LASTNAME_FIELD
match_count = 0
for results in readable_json['results']:
match_count += 1
if results['email'] == email_reference and results['email'] is not None and match_count != 1:
my_url = results['url']
my_cmd = 'http -a ' + login + ':' + password + ' PUT ' + my_url + ' firstname="' + new_firstname + '"' + ' lastname="' + new_lastname + '"'
p = subprocess.Popen(my_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
我的网站上有更多说明:https://hg-map.fr/astuces/69-django-rest-api