python - 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,但没有在父模型中存储子模型信息。
我该如何做到这一点?
谢谢
解决方案
该关系已由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
推荐阅读
- javascript - 从组件导航到不同的组件 [React]
- ios - 模型对象问题
- visual-studio-code - ANGULAR-CLI - 可视代码:未捕获的类型错误:无法读取未定义的属性“NODE_DEBUG”
- java - 当我尝试为活动设置工具栏时,设置了两个工具栏标题。需要一些关于删除其中一个的帮助
- java - 从corda中的交易中检索帐户名
- postgresql - 在联合 sql 查询中添加 Exists 运算符
- python - 排序日期时间列熊猫
- java - 内部有实体的弹簧投影
- python - Seaborn 热图轴的位数
- visual-studio-2012 - VS2012 无法使用 Nuget 管理器