Search code examples
pythondjangodjango-modelsdjango-formsdjango-admin

Django Admin - Show ManyToOne data on a model in admin


I have 2 models Patient and History. I would like to show all History of a Patient inside the Patient model in django admin as table. I was thinking to use ManyToOne field as one patient can have more than 1 history and 1 history is only owned by 1 patient. In the Patient model admin I would like to also be able to add a new history. I have tried to use ManyToMany field but doesn't looks like the solution. Can anyone please help me on how to solve this?

Below is the code:

class Patient(models.Model):
    name = models.CharField(max_length=100)

class History(models.Model):
    patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
    diagnosis = models.TextField()

Solution

  • You can use InlineModelAdmin objects to achieve this functionality, they allows us to edit models related to the parent model in the same form as the parent model.

    Try the following:

    from django.contrib import admin
    from .models import Patient, History
    
    @admin.register(History)
    class HistoryAdmin(admin.ModelAdmin):
        pass
    
    class HistoryInline(admin.TabularInline):
        model = History
        extra = 1
    
    @admin.register(Patient)
    class PatientAdmin(admin.ModelAdmin):
        inlines = [HistoryInline]