Django Inheritance and Permalinks

后端 未结 3 737
孤城傲影
孤城傲影 2021-01-07 05:25

I\'m creating a simple CMS in django, with multiple \"modules\" (each as a django app). I\'ve set up the following models:

class FooObject(models.Model):
            


        
相关标签:
3条回答
  • 2021-01-07 06:04

    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.

    0 讨论(0)
  • 2021-01-07 06:21

    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.

    0 讨论(0)
  • 2021-01-07 06:24

    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()
    
    0 讨论(0)
提交回复
热议问题