nielsrolf
nielsrolf

Reputation: 81

Add a set of related models to serializer output in django w djange-rest-framework

So I am just getting familiar with django and django-rest-framework. I have a model of Jobs that have an owner, and I want to add the list of jobs a user owns to the user endpoint.

I tried to do it like this, as the tutorial of the django rest framework says:

class UserSerializer(serializers.ModelSerializer):
    jobs = serializers.PrimaryKeyRelatedField(many = True, queryset = Job.objects.all())

    class Meta:
        model = User
        fields = ('id', 'username', 'jobs')

But for some reason, when I want to view the users, I recieve AttributeError at /users/ 'User' object has no attribute 'jobs'

The documentation about the PrimareyKeyRelatedField looks just like this. Do I maybe have to do something with the user model?

What works is the following:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'job_set')

but I don't like that solution as I want to have more control about how the list is presented (maybe change the ids to complete json objects or rename the attribut name from 'job_set' to 'job)

I really don't now what I am overseeing...

Upvotes: 1

Views: 618

Answers (1)

Sagar Ramachandrappa
Sagar Ramachandrappa

Reputation: 1461

You can do two things,

jobs = serializers.PrimaryKeyRelatedField(many = True, source='job_set' queryset = Job.objects.all())

or

Set related_name='jobs' attribute to User relational field.

Upvotes: 1

Related Questions