Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework -- How to resolve ForeignKey to Actual Value, not index?

I have a model such as:

class Job(models.Model):
    build = models.ForeignKey(Build, on_delete=models.PROTECT)
    name = models.CharField(blank=True, null=True)

and a view:

class JobViewSet(viewsets.ModelViewSet):
    queryset = Job.objects.all()
    serializer_class = JobSerializer

and a serializer:

class JobSerializer(serializers.ModelSerializer):
    class Meta:
        model = Job

The only issue is when I access the API endpoint, I receive data, but the build property from Job model is the actually integer of the foreign key. I want the actual value from that key (which is also a model in my Django rest framework.

I have search a lot and I found some promising articles, but was not getting correct results when I tried various things. I am still new to Django...Can any of you help?

like image 206
Rich Episcopo Avatar asked Mar 15 '23 05:03

Rich Episcopo


2 Answers

First create a serializer for Build like:

class BuildSerializer(serializers.ModelSerializer):
    class Meta:
        model = Build

Next in JobSerializer do like:

class JobSerializer(serializers.ModelSerializer):
    build = BuildSerializer()
    class Meta:
        model = Job
        fields = ('name','build')
like image 156
Anush Devendra Avatar answered Apr 16 '23 21:04

Anush Devendra


Use a depth attribute.

class BuildSerializer(serializers.ModelSerializer):
    class Meta:
        model = Build
        depth = 1
like image 36
Karan Kumar Avatar answered Apr 16 '23 22:04

Karan Kumar