[Answer]-Duplicate/Archive entry in Django to another model

1👍

With the help of @Igor’s comment I amended my solution to this:

def archive_calc(self, object_id):
    annual = InstrumentAnnual.objects.get(id = object_id)
    annual_archive = InstrumentAnnualArchive()

    for field in annual._meta.fields:
        setattr(annual_archive, field.name, getattr(annual, field.name))
    annual_archive.pk = None
    annual_archive.save()

It occured to me that using pre_save wouldn’t work as it is listening/linked to a model, not a view as I originally thought. So I placed the above code in my Update View and called it passing the id in object_id.

Thanks again for the help.

👤Karl

0👍

You should be using named arguments in your constructor, otherwise the first argument will be interpreted as the id, so try:

# omitted code
e = InstrumentAnnual.objects.filter(id=stored_id)
archive = InstrumentalAnnualArchive(field_name=e.field_name, another_name=e.another_field_name, …)
archive.save()

But you could also use Django’s create function, so:

# omitted code
e = InstrumentAnnual.objects.filter(id=stored_id)
archive = InstrumentalAnnualArchive.objects.create(field_name=e.field_name, another_name=e.another_field_name, …)

This way handles the save for you, so you don’t need to explicitly save your object.

Leave a comment