Home > OS >  Django - multi-table inheritance - convert Parent to Child
Django - multi-table inheritance - convert Parent to Child

Time:06-11

I have models that look like this:

class Property(Model):
    ...
    class Meta:
        # not abstract

class Flat(Property):
    ...

class House(Property):
    ...

Is it possible to convert already existing Property to House or Flat? I know that House or Flat additional fields are in different tables so this should be doable by creating such a row and making some relation.

How can I do that?

CodePudding user response:

With a custom method?

class Property(...):

    ...
    def convert_to_house(self):

        # create a house
        house = House.objects.create(
            ...
        )

        # delete current property:
        self.delete()

CodePudding user response:

Creating a new House and deleting Property is not a good way to go for multiple reasons. One of them is that the Property object may be already involved in relationships with other models/object.

This looks to be working to me:

child = House(property_ptr=property, created=now())
child.save()

As a DRF custom action it looks like this:

@action(['POST'], detail=True, url_path='create-child')
def create_child(self, request, pk=None):
    property = self.get_object()
    if property.get_child():
        raise APIException(detail="Blah blah")
    _type = request.data.get('type')

    try:
        ChildModel = Property.get_subtypes_map()[_type]
    except KeyError:
        raise APIException(detail="Blah blah")
    child = ChildModel(property_ptr=property, created=now())
    child.save()
    return Response({'id':child.id})

PS: You also should check if the model already has any child.

  • Related