首页 > 解决方案 > Django admin继承,在父模型中引用子模型id

问题描述

我有一个基本模型和 2 个从基本模型继承的子模型

class Module(models.Model):

    name = models.CharField(max_length=200, null=False)

    def __str__(self):
        return self.name
        
class A(Module):

  title = models.CharField(max_length=300, null=False, verbose_name='Title')
  image = models.FileField(upload_to='uploads/', null=True)
  
  
class B(Module):

  title = models.CharField(max_length=300, null=False, verbose_name='Title')
  sub_title = models.CharField(max_length=300, null=False, verbose_name='Title')
  image = models.FileField(upload_to='uploads/', null=True)

这工作正常,Django 在子模型表中创建了引用父级的表。

现在,我遇到的困难是有一个额外的应用程序具有自己的模型,需要查询相关的父模型及其所有子模型。让我们假设这是我的应用程序引用模块类

class Page(models.Model):


    title = models.CharField(max_length=300, null=False)
    slug = models.SlugField(max_length=300, null=False, db_index = True)
    modules = models.ManyToManyField('modules.module')
   

通过当前的设置,Django 将父模型 ID 存储在子模型表中,我没有在客户端使用 django,因此在我的 sql 查询中,我想通过引用什么子模型来将子模块附加到父模块是指。请记住,Parent 仅与一个模型相关联。

我查看了抽象、代理模型以及 model_utils.managers InheritenceManager,但没有在父模型中存储子模型信息。

我该如何做到这一点?

谢谢

标签: pythondjangopython-3.xdjango-admin

解决方案


该关系已由ManyToManyField. 能够显示它可能是您遇到的问题。

您可以引用“通过”模型并在 Admin 中注册它,如下所示:

from django.contrib import admin


# https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#inlinemodeladmin-objects
#
# You can use TabularInline, or StackedInline --- whichever meets your style preferences
#
class PageModuleInline(admin.TabularInline):
    model = Page.modules.through  # the implicit "join table" model

class PageAdmin(admin.ModelAdmin):
    inlines = [
        PageModuleInline,
    ]

class ModuleAdmin(admin.ModelAdmin):
    inlines = [
        PageModuleInline,
    ]

见:https ://docs.djangoproject.com/en/3.0/ref/contrib/admin/#working-with-many-to-many-models


推荐阅读