Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 207
leech Avatar asked Dec 05 '22 16:12

leech


1 Answers

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

like image 128
Davide Callegari Avatar answered Jan 22 '23 14:01

Davide Callegari