Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django foreign key

Tags:

django

I have the following in my 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

I have the following in my 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)

What I want is to display the fields under the component description to be displayed under the lab title(the fields related to each lab title by should be displayed under that lab name)

like image 568
user2148571 Avatar asked Mar 09 '26 16:03

user2148571


1 Answers

What you are doing with list_display and list_filter pertain to the list that is shown in the admin screen where the list of LabName objects are listed.

Assuming one LabName has one-to-many ComponentDescription entities, you need Django's InlineModelAdmin to display the list of ComponentDescription objects belonging to LabName within the admin page for a specific LabName entity. The code would be of the following structure:

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)

where TabularInline is a subclass of the generic InlineModelAdmin.

like image 164
Joseph Victor Zammit Avatar answered Mar 11 '26 08:03

Joseph Victor Zammit