0

Let's say I have the following Listing model. I retrieve a listing and store that in old_listing, and set up a new one and store that in new_listing. Now is there some way to save new_listing into old_listing, basically overriding all fields except the auto-incrementing id field?

class Listing(models.Model):
   street = models.CharField(max_length=500)

old_listing = Listing.objects.get(id=1) # Assuming this record already exists
new_listing = Listing(street='123 Main Street')

old_listing.save(new_listing) # This obviously doesn't work
Valachio
  • 1,025
  • 2
  • 18
  • 40
  • Why do you want to do this? – Daniel Roseman Jan 27 '18 at 19:59
  • @DanielRoseman Because the actual `Listing` model has a lot of fields, and many fields require custom cleaning logic. This way I can avoid having to copy and paste many of the logic. – Valachio Jan 27 '18 at 20:19
  • But that appears to be the opposite of what you've described in the question. You say you want to override all the fields of the *old* object with the new one. – Daniel Roseman Jan 27 '18 at 20:23
  • @DanielRoseman Yes. Before I add a listing, I first check if an older version of the same listing exists. If it does exist, then I need to update the old listing with the newer listing. This is where I can choose between several options, like the option I mentioned in my question, or the answers listed on a question like this - https://stackoverflow.com/questions/2712682/django-update-object. It would seem my method would be the easiest for my situation, if it is possible. – Valachio Jan 27 '18 at 20:29

1 Answers1

0
new_listing.id = old_listing.id
new_listing.save()

This should work.

Abhishek Menon
  • 753
  • 4
  • 15