I'm implementing a simple platform sales, one section of this platform references to insert the many orders that are set up, this orders (Pedido
) are related to an order_detail (Detalle_Pedido
) and this to product (Producto
) like this:
class Pedido(models.Model):
referencia = models.CharField(max_length=255)
cliente = models.ForeignKey(Cliente,related_name="cliente")
fecha_pedido = models.DateField(auto_now=True)
fecha_entrega = models.DateField(auto_now=True)
agencia_envio = models.ForeignKey(Envio, related_name="entrega",blank=True,null=True)
producto = models.ManyToManyField(Producto, through='Detalle_Pedido')
def __unicode__(self):
return self.referencia
class Meta:
ordering = ["referencia","fecha_pedido"]
class Detalle_Pedido(models.Model):
pedido = models.ForeignKey(Pedido, related_name="pedido")
producto = models.ForeignKey(Producto, related_name="producto")
unidad_precio = models.FloatField()
cantidad = models.IntegerField()
descuento = models.FloatField(blank=True)
def __unicode__(self):
return self.producto
class Meta:
ordering = ["producto"]
class Producto(models.Model):
referencia = models.CharField(max_length=30)
nombre = models.CharField(max_length=500)
cantidad = models.IntegerField()
precio_unidad = models.FloatField(blank=True)
cantidad_en_pedido = models.IntegerField(blank=True)
descatalogado = models.BooleanField(blank=True)
proveedor = models.ForeignKey(Proveedor,related_name="proveedor",blank=True,null=True)
categoria = models.ForeignKey(Categoria,related_name="categoria",blank=True,null=True)
imagen = models.ImageField(upload_to="/media/productos", blank=True)
def __unicode__(self):
return self.nombre
class Meta:
ordering = ["nombre","cantidad","precio_unidad","cantidad_en_pedido","descatalogado"]
Every time an order in Pedido
is created, through Detalle_Pedido
I have to relate each order detail with the new created order and when create each order detail relate with a Producto
so user can set the product and quantity for the order detail, I'm using a CreateView
, I know this could be do with formsets
but I see examples and I'm not clarify with the fact of use with ManyToManyFields
through a model, in this case, Detalle_Pedido
Edit:
I'm clarify some issues for make more understanding, first of all Detalle_Pedido
, yes, is an item part of an order that's why I define a foreign key targeting to Pedido
(an order), an order has many items, Detalle_Pedido
(order detail) has another foreign key targeting to Producto
(product) for retrieve the product details, from Pedido
I did a ManyToManyField
to Producto
because one order have some products and for that, i set the clause through
saying that I want to store some data related to the order and product, that's the order detail (Detalle_Pedido
), I don't know if that's the more "legit" way to do that but is a little approach for what I'm trying to do, I'm relative new in Django so I miss many things, any advice or tip would be more appreciated.