简体   繁体   中英

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM