How to display names instead of IDs, using Django with React?

I'm using Django with React.

I'm creating a CRUD application for products. My Product table is related to the Category, Brand, Model, Quality, and Supplier tables.

I can save the data, but when I try to view it, it shows the IDs (category, brand, model, quality, supplier) instead of the names.

Here's the code.

Serializer.py

class ProductoSerializer(serializers.ModelSerializer):
  categoria = serializers.PrimaryKeyRelatedField(queryset=Categoria.objects.all())
  marca = serializers.PrimaryKeyRelatedField(queryset=Marca.objects.all())
  modelo = serializers.PrimaryKeyRelatedField(queryset=Modelo.objects.all())
  calidad = serializers.PrimaryKeyRelatedField(queryset=Calidad.objects.all())
  proveedor = serializers.PrimaryKeyRelatedField(queryset=Proveedor.objects.all())


  class Meta:
      model = Producto
      fields = [
          'id',
          'nombre',
          'precio',
          'stock',
          'categoria',
          'marca',
          'modelo',
          'calidad',
          'proveedor'
      ]

ProductoCard.jsx

import { useNavigate } from 'react-router'


export function ProductoCard({ producto}) {

    const navigate = useNavigate();

    return (
        <div>
            <h3>Nombre: {producto.nombre} </h3> 
            <h3>Precio: {producto.precio}</h3>
            <h3>Stock: {producto.stock}</h3>
            <h3>Categoria: {producto.categoria}</h3>
            <h3>Marca: {producto.marca}</h3>
            <h3>Modelo: {producto.modelo}</h3>
            <h3>Calidad: {producto.calidad}</h3>
            <h3>Proveedor: {producto.proveedor}</h3>
            <hr />
        </div>
    )

}

ProductoFormPage.jsx

import { useEffect, useState } from "react";
import { Link, useNavigate, useParams } from "react-router";
import { createProducto, getProducto, updateProducto } from "../../api/producto.api";
import { getAllCategorias } from "../../api/categoria.api";
import { getAllMarcas  } from "../../api/marca.api";
import { getAllModelos } from "../../api/modelo.api";
import { getAllCalidades } from "../../api/calidad.api";
import { getAllProveedores } from "../../api/proveedor.api";


export function ProductoFormPage() {
    
    const [productos, setProductos] = useState({
        nombre: "",
        precio: "",
        stock: "",
        categoria: "",
        marca: "",
        modelo: "",
        calidad: "",
        proveedor: "",
    });


    const [categorias, SetCategorias] = useState([]);
    const [marcas, setMarcas] = useState([]);
    const [modelos, setModelos] = useState([]);
    const [calidades, setCalidades] = useState([]);
    const [proveedores, setProveedores] = useState([]);


    const navigate = useNavigate()
    const params = useParams()

    useEffect(() => {
        const loadProducto = async () => {
            if (params.id) {
                const response = await getProducto(params.id)
                setProductos(response.data)
            }
        }

        const loadCategoria = async () => {
            const response = await getAllCategorias();
            SetCategorias(response.data);
        }

        const loadMarca = async () => {
            const response = await getAllMarcas();
            setMarcas(response.data);
        }

        const loadModelo = async () => {
            const response = await getAllModelos();
            setModelos(response.data)
        }
        
        const loadCalidad = async () => {
            const response = await getAllCalidades();
            setCalidades(response.data);
        }

        const loadProveedor = async () => {
            const response = await getAllProveedores();
            setProveedores(response.data);
        }


        loadProducto();
        loadCategoria();
        loadMarca();
        loadModelo();
        loadCalidad();
        loadProveedor();

    }, [params.id])

        

    const handleSubmint = async (e) => {
        e.preventDefault()
        

        
        if (params.id) {
            await updateProducto(params.id, productos);
        } else {
             await createProducto(productos);
        }

        navigate('/productos');
       
    };



    return (

        <div>
            <form onSubmit={ handleSubmint }>
                <h3>Nombre:</h3>
                <input
                    value={productos.nombre}
                    type="text"
                    onChange={(e) => setProductos({ ...productos, nombre: e.target.value })}
                    placeholder="Nombre del producto"
                    required={true}
                />
                <h3>Precio:</h3>
                <input
                    value={productos.precio}
                    type="text"
                    onChange={(e) => setProductos({ ...productos, precio: e.target.value })}
                    placeholder="Precio"
                    required={true}
                />
                <h3>Cantidad:</h3>
                <input
                    value={productos.stock}
                    type="text"
                    onChange={(e) => setProductos({ ...productos, stock: e.target.value })}
                    placeholder="Cantidad"
                    required={true}
                />
                <h3>Categoría:</h3>
                <select
                    value={productos.categoria}
                    onChange={(e) => 
                        setProductos({ ...productos, categoria: e.target.value })}
                >    
                    <option value="">---------Categoría---------</option>

                    {categorias.map(categoria => (
                        <option key={categoria.id} value={categoria.id}>
                            {categoria.nombre}    
                        </option>  
                       
                    ))}
                </select>

                <h3>Marca</h3>
                <select
                    value={productos.marca}
                    onChange={(e) =>
                        setProductos({ ...productos, marca: e.target.value })}
                >
                    <option value="">--------Marca--------</option>

                    {marcas.map(marca => (
                        <option key={marca.id} value={marca.id}>
                            {marca.nombre}
                        </option>
                    ))}
                </select>

                <h3>Modelo</h3>    
                <select
                    value={productos.modelo}
                    onChange={(e) =>
                        setProductos({ ...productos, modelo: e.target.value })}
                >
                    <option value="">--------Modelo--------</option>

                    {modelos.map(modelo => (
                        <option key={modelo.id} value={modelo.id}>
                            {modelo.nombre}
                        </option>
                    ))}
                </select>

                <h3>Calidad</h3>
                <select
                    value={productos.calidad}
                    onChange={(e) =>
                        setProductos({ ...productos, calidad: e.target.value})
                    }
                >
                    <option value="">--------Calidad--------</option>
                    {calidades.map(calidad => (
                        <option key={calidad.id} value={calidad.id}>
                            {calidad.nombre}
                        </option>
                    ))}

                </select>

                <h3>Proveedor</h3>
                <select
                    value={productos.proveedor}
                    onChange={(e) =>
                        setProductos({ ...productos, proveedor: e.target.value})
                    }
                >
                    <option value="">--------Proveedor--------</option>
                    {proveedores.map(proveedor => (
                        <option key={proveedor.id} value={proveedor.id}>
                            {proveedor.nombre}
                        </option>
                    ))}

                </select>
                <button>Guardar</button>
                <Link to="/productos">Cancelar</Link>
                
                

            </form>
        </div>
    
    )

}

How can I make it show names instead of IDs?

If you want to see the object instead of the id, you should use serializers.StringRelatedField, not serializers.PrimaryKeyRelatedField.

https://www.django-rest-framework.org/api-guide/relations/#inspecting-relationships

Depending on which field you want to show, you may need to adjust the __str__()

def __str__(self):
    return self.nombre
Вернуться на верх