Django外键

3

我在models.py中有以下内容:

from django.db import models

class LabName(models.Model):
    labsname=models.CharField(max_length=30)
    def __unicode__(self):
     return self.labsname

class ComponentDescription(models.Model):
       lab_Title=models.ForeignKey('Labname')
       component_Name = models.CharField(max_length=30)
       description = models.CharField(max_length=20)
        purchased_Date = models.DateField()
       status = models.CharField(max_length=30)
       to_Do = models.CharField(max_length=30,blank=True) 
       remarks = models.CharField(max_length=30)

       def __unicode__(self):
           return self.component

我在我的admin.py中有以下内容:

from django.contrib import admin
from Lab_inventory.models import ComponentDescription,LabName

class ComponentDescriptionAdmin(admin.ModelAdmin):
    list_display= ('lab_Title','component_Name','description','purchased_Date','status','to_Do','remarks')          
    list_filter=('lab_Title','status','purchased_Date')

admin.site.register(LabName)
admin.site.register(ComponentDescription,ComponentDescriptionAdmin)

我想要的是在实验室标题下方显示与该实验室相关的字段(每个实验室标题下的相关字段都应该显示在该实验室名称下方)。
1个回答

1
你正在使用 list_displaylist_filter 来处理在管理界面中显示的列表,其中列出了 LabName 对象的列表。
假设一个 LabName 有一对多个 ComponentDescription 实体,你需要使用 Django 的 InlineModelAdmin 来在特定 LabName 实体的管理页面上显示属于其的 ComponentDescription 对象列表。代码结构如下:
from django.contrib import admin
from Lab_inventory.models import ComponentDescription,LabName

class ComponentDescriptionInline(admin.TabularInline):
    model = ComponentDescription

class LabNameAdmin(admin.ModelAdmin):
    inlines = [
        ComponentDescriptionInline,
    ]

admin.site.register(LabName, LabNameAdmin)

其中TabularInline是通用InlineModelAdmin的子类。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接