Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
How to display a foreign key value instead of the id?

I have the following models :

class FlightSchedule(models.Model):
    tail_number = models.ForeignKey(TailNumber, null=False)
    flight_number = models.CharField(max_length=30, null=False)
    flight_group_code = models.ForeignKey(FlightGroup, null=False)
    origin_port_code = models.ForeignKey(Port, null=False, related_name="Origin")
    destination_port_code = models.ForeignKey(Port, null=False, related_name="Destination")
    flight_departure_time = models.TimeField()
    start_date = models.DateField()
    end_date = models.DateField()

def __unicode__(self):
    return u'%s' % self.flight_number

class Meta:
    verbose_name_plural = "Flight Schedule"


class FlightScheduleDetail(models.Model):
    flight_date = models.CharField(max_length=30, null=False)
    flight_number = models.ForeignKey(FlightSchedule, null=False, related_name="flight_number_schedule")
    route_id = models.CharField(max_length=30, null=False, unique=True)
    flight_status = models.ForeignKey(Status, null=True, default=1)

def __unicode__(self):
    return u'%s' % self.route_id

class Meta:
    verbose_name_plural = "Flight Schedule Details"

and the serializer is as below :

class FlightScheduleDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = FlightScheduleDetail
        fields = '__all__'


class FlightScheduleSerializer(serializers.ModelSerializer):
    flight_number_schedule = FlightScheduleDetailSerializer(many=True)

    class Meta:
        model = FlightSchedule
        fields = ['tail_number', 'flight_number', 'origin_port_code', 'destination_port_code', 'flight_departure_time',
              'flight_number_schedule']

Here tail_number , flight_number is a foreign key. When I create an API, I get the response as the id of the fields. How can I display the name in the json?

My views.py is as below :

@api_view(['GET'])
def flight_schedule(request):
    schedule = FlightSchedule.objects.all()
    serializer = FlightScheduleSerializer(schedule, many=True)
    return Response(serializer.data)
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You can define the source with field_name in your serializer as follows.

I have used source='TailNumber.number'. Please use the right field_name in place of number

class UserProfileSerializer(serializers.ModelSerializer):
    tail_number = serializers.CharField(source='TailNumber.number', read_only=True)
    flight_number = ....(change as above)

    class Meta:
        model = FlightSchedule
        fields = ['tail_number', 'flight_number', 'origin_port_code', 'destination_port_code', 'flight_departure_time',
          'flight_number_schedule']
over 4 years ago · Santiago Trujillo Report

0

You could simply add them as if they were attributes.

flight_number_str = serializers.ReadOnlyField(source='flight_number.flight_number')

First flight_number is the attribute of FlightScheduleDetail, then the one of FlightSchedule

and then add it to the list of fields fields = [..., 'flight_number_str']

Otherwise you may have a look at nested relationships in DRF which can offer more possibilities also.

over 4 years ago · Santiago Trujillo Report

0

Another alternative is to use the depth option in a serializer. It is to specify nested serialization - doc

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = ('id', 'account_name', 'users', 'created')
        depth = 1

If users is a foreign key or manytomany key the serializer will display the users as an object and not as a key.

The depth option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!