user2148571
user2148571

Reputation: 129

django foreign key

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)

Upvotes: 3

Views: 126

Answers (1)

Joseph Victor Zammit
Joseph Victor Zammit

Reputation: 15320

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.

Upvotes: 1

Related Questions