Login

Snippets by bronger

Snippet List

Get actual child model in multi-table inheritance

A common problem (it hit the Django mailinglist a couple of times) is that if you get `models.Topping.objects.all()`, you get a list of toppings, although they stand for other classes such as `SalamiTopping` or `CheeseTopping`. If you need the actual object, just derive `Topping` from `PolymorphicModel`, and say `topping.actual_instance`. This will give you e.g. a `SalamiTopping`. Sometimes you just want to check for the actual class. You can get it by saying `topping.content_type.model_class()`. There is a slight performance impact when creating objects because they have to be saved twice. NEWS: A good alternative to this approach is the [InheritanceManager](https://github.com/carljm/django-model-utils/blob/master/README.rst).

  • models
  • child-model
  • multi-table-inheritance
  • polymorphy
Read More

bronger has posted 1 snippet.