问题
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?
回答1:
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?
来源:https://stackoverflow.com/questions/22003827/how-to-get-a-field-of-a-foreign-key-model-appear-in-a-django-serializer