Django Inheritance and Permalinks

為{幸葍}努か 提交于 2019-12-01 01:03:12

The classic solution to this problem tends to be adding a ContentType to the superclass which stores the type of subclass for that instance. This way you can rely on a consistent API that returns the related subclass object of the appropriate type.

You can avoid adding a content type field by using the InheritanceManager from django-model-utils.

Then, if you call .select_subclasses on a queryset, it will downcast all of the objects, for example:

FooPage.objects.select_subclasses().all()

FooPage.objects.all() returns all the objects of type FooPage, these objects will be mix of underlying db table rows for FooPage, FooBlog, FooGallery. To get the correct URL you should get the FooBlog or FooGallery object e.g.

page.fooblog.get_absolute_url()

it may throw FooBlog.DoesNotExist error if page is simply a page object i.e created via FooPage, so to get correct urls you may do something like this

   urls = []
   for page in FooPage.objects.all():
        try:
            page = page.fooblog
        except FooBlog.DoesNotExist:
            pass

            urls.append(page.get_absolute_url())

alternatively you may try to make FooPage a abstractclass if you do not want FooPage to be a real table.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!