如何获取一个外键字段的模型出现在Django-Serializer中? [英] How to get a field of a foreign key Model appear in a Django-Serializer?
问题描述
我正在构建一个公开一个REST API的Django应用程序,用户可以通过该API访问我的应用程序模型2。我遵循 这里 的说明。
我的两个模型是:
- 来自django.contrib的Django用户模型.auth
-
模型如下所示。
模型):
user = models.OneToOneField(User)
我的串行程序如下:
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta :
model = User
fields =('url','username','email')
class ProfileSerializer(serializers.HyperlinkedModelSerializer):
class Meta :
model = Profile
fields =('id','slug','user',)
我可以看到,当我从命令行点击API时,这是正常工作:
%curl -H'Accept:application / json; indent = 4'-u root:MyPassword http://127.0.0.1:3001/api/profiles/60/
/ pre>
{
id:60,
slug:myprofile ,
user:http://127.0.0.1:3001/api/users/16/
}
%curl -H'Accept:application / JSON; indent = 4'-uroot:MyPassword http://127.0.0.1:3001/api/users/16/
{
url:http://127.0.0.1:3001/api/用户/ 16 /,
username:myUser,
email:myemail@gmail.com
}
我想知道的是两件事:
- 如何公开这个API,即使没有root / password登录,也可以使用该用户的用户名?
解决方案问题#1正确回答:如何在外键的查询详细信息字段中包含( django和rest_api)
问题#2在这里重新询问:如何管理访问Django REST API的权限?
I am building a Django application that exposes a REST API by which users can query 2 of my application's models. I'm following the instructions here.
My two models are:
- The Django User model from django.contrib.auth
The model shown below.
class Profile(models.Model): user = models.OneToOneField(User)
My Serialiazers are as follows:
class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', ) class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = ('id', 'slug', 'user',)
I can see that this is working when I hit the APIs from the command-line:
% curl -H 'Accept: application/json; indent=4' -u root:MyPassword http://127.0.0.1:3001/api/profiles/60/ { "id": 60, "slug": "myprofile", "user": "http://127.0.0.1:3001/api/users/16/" } % curl -H 'Accept: application/json; indent=4' -uroot:MyPassword http://127.0.0.1:3001/api/users/16/ { "url": "http://127.0.0.1:3001/api/users/16/", "username": "myUser", "email": "myemail@gmail.com" }
What I would like to know are two things:
- How do I change my Profile's serializer such that the user's username appears in the serialized profile?
- How can I expose this API publicly so it works even without the root/password login?
解决方案Question #1 Answered correctly here: How to include in queryset details fields of a foreign key (django and rest_api)
Question #2 Re-asked more clearly here: How are permissions to access to Django REST API managed?
这篇关于如何获取一个外键字段的模型出现在Django-Serializer中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!