How to get a field of a foreign key Model appear in a Django-Serializer?

只愿长相守 提交于 2019-12-25 04:26:35

问题


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:

  1. The Django User model from django.contrib.auth
  2. 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:

  1. How do I change my Profile's serializer such that the user's username appears in the serialized profile?
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!