Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
Django - how to save method apply only on new data

How do I manipulate this method to be applied only on new entries and does not have a previous entry.

When in admin, I will add an record, this method is applied correctly. but when I edit the same record, this method is applied again.

def save(self):
    p = Product.objects.last()
    if p:
        self.productnumber = 1000 + p.id
    else:
        self.productnumber = 1000
    super(Product, self).save()
about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Two ways are there.

1. post_save

@receiver(post_save, sender= Product)
def my_callback(sender, instance, created, *args, **kwargs):
    if created:
        #new
    else:
        #update

2. check primary key exists

def save(self):
    if self.pk: #or id
        #update
    else:
        #new
about 4 years ago · Santiago Trujillo Denunciar

0

If you want to execute some code in the save() method, only for non-existing items you should check if a primary key exists.

def save(self):
    if self.pk is None:
        # Code for new objects
    else:
        # Code for existing objects
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda