Hi, i have a model with a manytomany relationship to another and i would like to know if it is possible to set a method to get all of these related objects (If possible with attribute filtering to get only certain fields in the results).
I have this model:
class Pedido(models.Model):
"""Clase que crea instancias de pedidos en la base de datos"""
ESTATUS_PEDIDO= [
('ENPROCESO', 'Pedido en Proceso'),
('CANCELADO', 'Pedido Cancelado'),
('COMPLETADO','Pedido Completado'),
]
cliente = models.ForeignKey(User, related_name='cliente', on_delete=models.CASCADE)
repartidor = models.ForeignKey(User, related_name='repartidor', on_delete=models.CASCADE, blank=True, null=True)
direccion_de_recogida = models.CharField(max_length=50)
direccion_de_entrega = models.CharField(max_length=50)
hora_de_recogida = models.TimeField(auto_now=False)
estado = models.CharField(max_length=15, choices=ESTATUS_PEDIDO, default='ENPROCESO')
informacion_extra = models.TextField(max_length=50, blank=True, null=True)
tiempo_de_reparto = models.CharField(max_length=10, blank=True, null=True)
fecha_creacion = models.DateTimeField(auto_now_add=True)
costo_pedido = models.FloatField(blank=True, null=True)
And this other with a manytomany relationship:
class OrdenDeServicio(models.Model):
"""Clase que crea la orden del servicio. Incluye una relaciĂłn many to many a los pedidos y una foreignk key al cliente"""
ESTATUS_ORDEN = [
('ENPROCESO', 'Orden en Proceso'),
('ENREPARTO', 'Orden en Reparto'),
('CANCELADA', 'Orden Cancelada'),
('COMPLETADA','Orden Completada'),
]
cliente = models.ForeignKey(User, related_name='orden_cliente', on_delete=models.CASCADE)
**pedido = models.ManyToManyField(Pedido, related_name='pedidos')**
estado = models.CharField(max_length=10, choices=ESTATUS_ORDEN, default='ENPROCESO')
payment_intent_id= models.CharField(max_length=300, blank=True, null=True)
total_a_pagar = models.FloatField(max_length=4, blank=True, null=True)
forma_de_pago = models.CharField(max_length=30, blank=True, null=True)
creada = models.DateTimeField(auto_now=True)
pagada = models.DateTimeField(auto_now_add=False, blank=True, null=True)
def __str__(self):
return f'Cliente: {self.cliente} - NĂşmero de Orden: {self.id} '
I would like to create a function in OrdenDeServicio which makes what i’ve mentioned above, let’s say i want to get all the related Pedido instances “direccion_de_entrega” to put them into a list and use them in a view.
Thans, i appreciate your help.
Cheers.