djangodjango-modelsdjango-ormmulti-table-inheritance

how to copy an object using multi table inheritance in django


I am trying to copy an object that extends another object through multi table inheritance.

The parent is Group and the child is Location

The problem is that the parent object is changed instead of creating a new parent and child object.

Here is what I am doing:

location = get_object_or_404(Location, pk=pk)

        location.pk = None
        location.name = location.name+' - child object'
        location.save()

Instead of creating a new location and group row in their respective tables, this updates the group table to have the name = name + ' - child object'.

how can I have this process create a new location and group row instead of updating the Group row?

Thanks!


Solution

  • The key here is that multi-table inheritance in Django is implemented using foreign keys, so an object that "inherits" another model is simply ForeignKey'ed to that other model. You'll need to duplicate both.

    For how to do so, check out the solution in this answer.