'Django: Display inline through direct relation
I have models:
class CustomUser(AbstractUser):
employee_number = models.CharField(max_length=255, blank=True, db_index=True)
position = models.ForeignKey(
'orgunits.Position',
on_delete=models.CASCADE,
related_name='employees'
)
class Position(models.Model):
orgunit = models.ForeignKey(
OrgUnit,
on_delete=models.CASCADE,
verbose_name=_('orgunit'),
related_name='positions',
)
name = models.CharField(_('name'), max_length=255)
class OrgUnit(models.Model):
name = models.CharField(_('name'), max_length=255)
type = models.CharField(_('type'), max_length=55)
address = models.TextField(_('address'), null=True, blank=True)
I would like to display all CustomUser instances assigned to OrgUnit THROUGH Position:
class OrgUnitEmployeesInline(admin.TabularInline):
model = CustomUser
class OrgUnitAdmin(admin.ModelAdmin):
model = OrgUnit
inlines = OrgUnitEmployeesInline,
But of course there is an error:
<class 'orgunits.admin.OrgUnitEmployeesInline'>: (admin.E202) 'authentication.CustomUser' has no ForeignKey to 'orgunits.OrgUnit'.
because Position has ForeignKey to 'orgunits.OrgUnit'.
Also I tried this:
class OrgUnitEmployeesInline(admin.TabularInline):
model = CustomUser
fk_name = 'position'
but error:
<class 'orgunits.admin.OrgUnitEmployeesInline'>: (admin.E202) fk_name 'position' is not a ForeignKey to 'orgunits.OrgUnit'.
How can I display users in orgunits inline?
Solution 1:[1]
The closest thing in simple way is this:
class OrgUnitEmployeesInline(admin.TabularInline):
model = Position
fk_name = 'positions'
fields = ('employees', )
Otherwise you have to settle with custom forms.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
