在Django管理中显示外键对象内的相关数据 [英] Show related data inside foreign key object in django admin

查看:68
本文介绍了在Django管理中显示外键对象内的相关数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建学校管理系统.多个用户/school_owner将根据其学校中的班级数量创建多个班级.我是超级用户[即超级管理员],可以访问每所学校的课程.因此,我想链接特定学校的课程[即[外键]的特别链接.然后单击该链接,与外键链接的类将显示在列表中.

I am creating a school management system. Multiple users/school_owners will create multiple classes according to the number of classes in their school. I am the superuser [i.e. Super Admin] that can access classes in every school. So, I want to link classes of a particular school [i.e. Foreign Key] in particular link. And I'll press that link and the class linked with the foreign key will be display in the list.

admin 中应该是这样的:

  • 学校名称1
  • ---- 1类
  • ---- 2类
  • ---- 3类
  • ----第4类
  • 学校名称2
  • ---- 1类
  • ---- 2类
  • ---- 3类
  • ----第4类

此处学校名称1 学校名称2 是外键值.当我单击学校名称1"和学校名称2"时,他们应该将我重定向到各自的班级...

Here school name 1 and school name 2 are the foreign keys value. And when I click in school name 1 and school name 2 they should redirect me to their respective classes...

内部模型.py

from django.db import models
from accounts.models import school_details

class student_class(models.Model):
    connect_school = models.ForeignKey(school_details, on_delete=models.CASCADE, null=True)
    class_list = models.CharField(max_length=95)
    def __str__(self):
            return self.class_list

因此, connect_school [即学校名称]应该首先显示在 admin 中,当我们单击学校名称时,该特定类别的班级学校应该显示.

So, connect_school [i.e. school name] should be display first in the admin and when we click in school name the classes of that particular school should be displayed.

内部admin.py

Inside admin.py

from django.contrib import admin
from school.models import student_class
# Register your models here.
admin.site.register(student_class)

这张照片用上方的 admin.py 指示如何无序显示数据.

This photo denotes how that data is being displayed in an unorganized way with the upper admin.py.

推荐答案

解决此问题的最简单的方法是

The least hacky way to solve this, in my opinion, are admin inlines. Instead of pointing to another admin page, which kind of goes against the Django Admin structure, you can add inline editing interfaces for each class.

# admin.py

from django.contrib import admin
from accounts.models import school_details
from school.models import student_class


class ClassInline(admin.TabularInline):
    model = student_class


class SchoolDetailsAdmin(admin.ModelAdmin):
    model = school_details
    inlines = [ClassInline, ]


admin.site.register(school_details, SchoolDetailsAdmin)

这篇关于在Django管理中显示外键对象内的相关数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆