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?
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')
Use a depth
attribute.
class BuildSerializer(serializers.ModelSerializer):
class Meta:
model = Build
depth = 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With