I am programming a model that depends on another and I want that when modifying a specific field, it creates a new object based on the modified information.
My models are:
Order
class Pedido(models.Model):
id = models.BigAutoField(primary_key = True)
f_ped = models.DateTimeField(auto_now_add = True)
cp_nom_producto = models.CharField(max_length = 40)
estado_pedido = models.IntegerField(choices = CHOICES_ESTADO_PEDIDO, default = CHOICES_ESTADO_PEDIDO[0][0])
producto = models.ForeignKey(Producto)
perfil = models.ForeignKey(Perfil)
valoracion = models.OneToOneField(Valoracion, blank=True, null=True, on_delete = models.CASCADE)
slug = models.SlugField(blank=True, null=True)
num_guia = models.CharField(max_length = 12, blank=True, null=True)
fecha_entrega = models.DateTimeField(blank=True, null=True)
id_transaccion = models.CharField(max_length = 36, blank=True, null=True)
facturado = models.BooleanField(default = False)
def save(self, *args, **kwargs):
if self.id:
hash = hashlib.sha256(str(self.id).encode('utf-8'))
unique_slugify(self, hash.hexdigest())
super(Pedido, self).save(*args, **kwargs)
elif not self.id:
super(Pedido, self).save(*args, **kwargs)
Order Line
class LineaPedido(models.Model):
id = models.BigAutoField(primary_key = True)
pedido = models.ForeignKey(Pedido,on_delete=models.CASCADE)
estado = models.IntegerField(choices = CHOICES_ESTADO_PEDIDO)
fecha_creacion = models.DateTimeField(auto_now_add=True)
When the Order.order_status field changes I want to create an OrderLine object with the order information.
I guess doing what you want is not very complicated. To know if any property or field of your model or object has changed, I suppose you can know it in the method
save()
that would be in charge of saving the new state in memory of the object. But right there you can query the previous state of the object, like this: (I also show you an easier way to override your methodsave
removing redundancies)I hope I have helped you with this, any doubt, question or inconvenience, you can comment back and I will continue helping you