Copy fields from one instance to another in Django

2024/10/4 19:28:45

I have the following code which takes an existing instance and copies, or 'archives' it, in another model and then deletes it replacing it with the draft copy.

Current Code

def archive_calc(self, rev_num, primary_field):model_a = Calc.objects.get(tag_number__tag_number = primary_field, revision_number = rev_num) #Current Revision instancemodel_b = CalcArchive() #Draft instance#Copies data to archive modelfor field in model_a._meta.fields:setattr(model_b, field.name, getattr(model_a, field.name))model_b.pk = Nonemodel_b.current_revision = Falsemodel_b.save()model_a.delete()

This works fine however i need to change the system to allow for certain models with foreign keys as when an instance is archived/deleted the related records are deleted along with it. So my idea to fix this is to have the changes from the draft record copied to the previous record and then have the draft deleted thus maintaining the foreign key related records.

Solution idea

def archive_calc(self, rev_num, primary_field):model_a = Calc.objects.get(tag_number__tag_number = primary_field, revision_number = rev_num) #Current Revision instancemodel_b = CalcArchive() #Archive Instancemodel_c = Calc.objects.get(pk = self.object.pk) #Draft instance#Copies data to archive modelfor field in model_a._meta.fields:setattr(model_b, field.name, getattr(model_a, field.name))model_b.pk = Nonemodel_b.current_revision = Falsemodel_b.save()#Copies data from draft instance to current revision instancefor field in model_c._meta.fields:setattr(model_a, field.name, getattr(model_c, field.name))model_c.delete()

Unfortunately the above solution doesn't work, it just seems to ignore the copy and continues to work as per 'Current Code'. If I add model_a.save() after for field in model_c._meta.fi... the system gets stuck in a loop and eventually throws maximum recursion depth exceeded in cmp.

Any help would be much appreciate as usual and if im barking up the wrong tree please let me know.

Answer

After alot of poking around and reading the Django docs I have come up with what seems to be a pretty nice, simple solution.

def archive_calc(self, rev_num, primary_field):model_a = Calc.objects.get(calc_details__calc_serial_number = primary_field, revision_number = rev_num)model_b = CalcArchive()object_list_annual = model_a.calcreview_set.filter(calc__calc_details = primary_field)object_list_ageing = model_a.calcitem_set.filter(calc__calc_details = primary_field)for obj in object_list_annual:obj.calc_id = self.object.idobj.save()for obj in object_list_ageing:obj.calc_id = self.object.idobj.save()for field in model_a._meta.fields:setattr(model_b, field.name, getattr(model_a, field.name))model_b.pk = Nonemodel_b.current_revision = Falsemodel_b.save()model_a.delete()

This 'moves' the related objects by setting the _id fields to the same as self.object.id.

Ive ran several tests and this seems to achieve exactly what I was looking for with minimal code and no extra installs.

Hope this helps someone and please feel free to point out any potential pitfalls in my answer.

https://en.xdnf.cn/q/70578.html

Related Q&A

Python selenium get Developer Tools →Network→Media logs

I am trying to programmatically do something that necessarily involves getting the "developer tools"→network→media logs. I will spare you the details, long story short, I need to visit thou…

deep copy nested iterable (or improved itertools.tee for iterable of iterables)

PrefaceI have a test where Im working with nested iterables (by nested iterable I mean iterable with only iterables as elements). As a test cascade considerfrom itertools import tee from typing import …

ImportError: No module named cv2.cv

python 3.5 and windows 10I installed open cv using this command :pip install opencv_python-3.1.0-cp35-cp35m-win_amd64.whlThis command in python works fine :import cv2But when i want to import cv2.cv :i…

Why arent persistent connections supported by URLLib2?

After scanning the urllib2 source, it seems that connections are automatically closed even if you do specify keep-alive. Why is this?As it is now I just use httplib for my persistent connections... bu…

How to find accented characters in a string in Python?

I have a file with sentences, some of which are in Spanish and contain accented letters (e.g. ) or special characters (e.g. ). I have to be able to search for these characters in the sentence so I can…

Import error with PyQt5 : undefined symbol:_ZNSt12out_of_rangeC1EPKc,versionQt_5

I had watched a video on YouTube about making your own web browser using PyQt5. Link to video: https://youtu.be/z-5bZ8EoKu4, I found it interesting and decided to try it out on my system. Please note t…

Python MySQL module

Im developing a web application that needs to interface with a MySQL database, and I cant seem to find any really good modules out there for Python.Im specifically looking for fast module, capable of h…

How to calculate correlation coefficients using sklearn CCA module?

I need to measure similarity between feature vectors using CCA module. I saw sklearn has a good CCA module available: https://scikit-learn.org/stable/modules/generated/sklearn.cross_decomposition.CCA.h…

cant open shape file with GeoPandas

I dont seem to be able to open the zip3.zip shape file I download from (http://www.vdstech.com/usa-data.aspx)Here is my code:import geopandas as gpd data = gpd.read_file("data/zip3.shp")this …

How to fix the error :range object is not callable in python3.6 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar q…