leech
leech

Reputation: 8431

Django model inheritance: Delete subclass keep superclass

When dealing whith model inheritance in django is it possible to remove a instance of model subclass, without removing the superclass itself?

Using the Django example, can you remove just the Resturaunt object and retain the Place object?

Upvotes: 5

Views: 3928

Answers (2)

marxin
marxin

Reputation: 3922

In Django 1.9 parameter keep_parents was added to model delete() function, so to keep parents just call:

restaurant.delete(keep_parents=True)

Docs: https://docs.djangoproject.com/en/1.10/ref/models/instances/#django.db.models.Model.delete

UPDATE:

Apparently, this feature is not working properly in Django 1.9, please see the comments.

Upvotes: 9

Davide Callegari
Davide Callegari

Reputation: 494

Yesterday I was looking for an answer to this question and I came up with this solution, which was enough for my problem but could be scaled up as needed.

Assuming you have a Restaurant and a Place django models, the way to delete a restaurant only without touching the row inside the Place's table is creating a "fake" Restaurant model like this:

class FakeRestaurant(models.Model):
    place_ptr = models.PositiveIntegerField(db_column="place_ptr_id", primary_key=True)
    serves_hot_dogs = models.BooleanField()
    serves_pizza = models.BooleanField()

    class Meta:
        app_label = Restaurant._meta.app_label
        db_table = Restaurant._meta.db_table
        managed = False

Now, you can retrieve objects from that table as if it had no bound external relationship:

place = Place.objects.get(pk=1)
restaurant = Restaurant.objects.get(pk=1)
fake_restaurant = FakeRestaurant.objects.get(pk=1)
fake_restaurant.delete()

fake_restaurant and restaurant won't exist anymore, place will remain untouched.

Cheers, Davide

Upvotes: 10

Related Questions