Django Admin TabularInline - Getting Foreign Key through a OneToOne Relationship

2.4k Views Asked by At

As shown below, I want to display one model (Attendance) in the admin change view of another (Event) as a TabularInline. However, Attendance doesn't have a direct ForeignKey pointing to Event. Rather, it has a OneToOne relationship with Registration, which in turn points to Event. Any simple ways of achieving this?

As you can see from the code, I tried to access the Event using a method, and pass it into the TabularInline class as fk_name, but it threw an error saying "'myapp.Attendance' has no field named 'get_fk'".

myapp/models.py

from django.db import models

class Event(models.Model):
    ...

class Registration(models.Model):
    event = models.ForeignKey(Event, on_delete=models.CASCADE)
    ...

class Attendance(models.Model):
    registration = models.OneToOneField(Registration, primary_key=True, one_delete=models.CASCADE)
    ...

    def get_fk(self): 
        return self.registration.event

myapp/admin.py

from django.contrib import admin

class AttendanceInline(admin.TabularInline):
    model = Attendance
    fk_name = 'get_fk'

class EventAdmin(admin.ModelAdmin):
    inlines = [AttendanceInline]

My current workaround is to add another 'event' ForeignKey to Attendance, but it seems redundant as the same data is already stored inside 'registration'.

Appreciate it if anyone could help!

1

There are 1 best solutions below

1
Neeraj Kumar On

fk_name should be field name that have Foreignkey relation according to documentation not any property of model.

https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin.fk_name