Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

227
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda