Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!