【问题标题】:Django admin inheritance, referencing child model id in parent modelDjango管理员继承,在父模型中引用子模型ID
【发布时间】:2020-05-15 16:25:23
【问题描述】:

我有一个基础模型和 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,但没有在父模型中存储子模型信息。

我如何做到这一点?

谢谢

【问题讨论】:

  • 如何将数据传递给客户端?如果是 JSON,您可能希望使用“ModelSerializer”查看django-rest-framework.org/api-guide/serializers/…,您可以定义返回给客户端的数据形状
  • 感谢您的评论,但我认为这不是我所追求的,无论我使用什么作为 API,我仍然认为应该有一种方法可以通过在父记录中存储子类 id 来反转关系.那么我在 API 级别或客户端使用什么并不重要。仅供参考,我在 Lambda 上使用 Flask
  • 因为它是“ManyToMany”,所以创建了一个基础表来存储关系(假设是关系数据库)您可以像Page.objects.prefetch_related('modules') 一样查询它,但它们不会“附加到父级” ",例如,如果将其转换为 dict。序列化程序允许您定义字典表示的外观(带有附加到页面的模块)
  • 没有优雅的方式来扭转这种关系吗?
  • 另外,related_name=%(app_label)s_%(class)s_related) 呢? @RedTwoon

标签: python django python-3.x django-admin


【解决方案1】:

该关系已由ManyToManyField 定义。能够显示这可能是您遇到的问题。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    • 2011-11-14
    • 2021-12-11
    相关资源
    最近更新 更多