2

I want to learn how to copy an object but also copy the object referencing to that object.

As an example (simplified): Model 1: version

  • id
  • name

Model 2: file

  • id
  • file name
  • file contents
  • foreign key pointing to version

Relationship: One version can have multiple files

So one software version can have multiple files. I want to duplicate a complete version. Currently I have the following:

def duplicate_version(request,id, MAC_address):
    new_version = Version.objects.get(pk=id)
    new_version.pk = None
    new_version.save()

    new_files = File.objects.get(version_id=id)  <-- here I get the error
    new_id = new_version.id
    new_files.version_id = new_id
    new_files.save()
    return get_all_versions(request, MAC_address)

I understand how to copy an object and change the id (=None). But how do I manage to duplicate all the related files?

Error I get: Exception Value: get() returned more than one File -- it returned 2!

2 Answers 2

4

First you should probably read this. The get() method returns only one object. What you need is the filter() method to get a queryset.

Second, as you will have a queryset you cant just do new_files.version_id = new_id. If your field is a foreign key, try something like below. If its a many to many, just do new_version.file_set.add(new_files):

def duplicate_version(request,id, MAC_address):
    new_version = Version.objects.get(pk=id)
    new_version.pk = None
    new_version = new_version.save()
    new_files = File.objects.filter(version_id=id)
    new_files.update(version_id=new_version.id)
    return get_all_versions(request, MAC_address)
Sign up to request clarification or add additional context in comments.

8 Comments

Then just use the update method like in the code I posted.
@ Mehdi B Ok thank you. I added "new_files.save()" as is assume it is stil needed?
queryset doesnt have a save method
Just use the sample code I posted. If you use update() you dont need save().Again, save is for a single object, like get()
The code changed the foreign key of the new files. But it doesn't duplicate them
|
3
def duplicate_version(request, pk, MAC_address):
    new_version = Version.objects.get(pk=pk)
    new_version.pk = None
    new_version.modification_date = datetime.datetime.now()
    new_version.save()

    new_files = File.objects.filter(version_id=pk)
    for file in new_files:
        file.version_id = new_version.pk
        file.pk = None
        file.save()
    return get_all_versions(request, MAC_address)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.