Keibry
Keibry

Reputation: 31

Adding field from joined model in Django rest

I am new to django rest framework.

I have a model Client and Project.

class Client(models.Model):
    name = models.CharField(max_length=100)


class Project(models.Model):
    client = models.ForeignKey(Client)
    name = models.CharField(max_length=100)

in my project/serializer:

class ProjectSerializer(CoreHyperlinkedModelSerializer):
    class Meta:
        model = Task
        fields = ('url', 'id', 'name')

in my project/views:

class ProjectViewSet(viewsets.ModelViewSet):
    queryset = Project.objects.order_by('name').all()
    serializer_class = ProjectSerializer

I want to be able to add the Client primary key in the ProjectSerializer so when creating in api browser view, I can be able to add new data.

Upvotes: 0

Views: 61

Answers (2)

Cagatay Barin
Cagatay Barin

Reputation: 3496

You have to add it to your Project Serializer. If you add the foreignkey to your fields, it will give you the primary key.

class ProjectSerializer(CoreHyperlinkedModelSerializer):
    class Meta:
        model = Task
        fields = ('url', 'id', 'name', 'client', )

Or, if you want to modify your client view in Project serializer, you can use nested serialization.

class ProjectSerializer(CoreHyperlinkedModelSerializer):
    client = serializers.SerializerMethodField()

    def get_client(self, obj):
        serializer = ClientSerializer(obj.client.objects.all())
        return serializer.data

    class Meta:
        model = Task
        fields = ('url', 'id', 'name', 'client', )

Upvotes: 1

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53981

This is probably not the way you should be doing things, but to get just the primary key, you could use a PrimaryKeyRelatedField:

class ProjectSerializer(...):
    client = serializers.PrimaryKeyRelatedField(queryset=Client.objects.all)

    class Meta:
        model = Project
        fields = ('url', 'id', 'name', 'client', )

Upvotes: 1

Related Questions