我需要作为% api/email/user@gmail.com;api/email/user2@gmail.com的user-detail url终结点,但它不起作用
如果我将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 thelookup_fieldattribute 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
发布于 2020-03-23 14:57:04
同样的问题,我处理如下。
我会使用电子邮件字段进行查找,但不可能在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
https://stackoverflow.com/questions/55714961
复制相似问题