如何在使用Django和 React时显示名称而不是ID?
我在用Django和 React。
我正在为产品创建一个CRUD应用。我的Product表与Category、Brand、Model、Quality和 Supplier表相关联。
我可以保存数据,但在查看时,它显示的是ID(category、brand、model、quality、supplier)而不是名称。
以下是代码。
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?
解决方案
如果你想看到对象而不是id,你应该使用serializers.StringRelatedField,而不是serializers.PrimaryKeyRelatedField。
https://www.django-rest-framework.org/api-guide/relations/#inspecting-relationships
根据你想要显示的字段,可能需要调整的 __str__()
def __str__(self):
return self.nombre
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。