Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin, accessing reverse many to many

I would like to have access to reverse many to many relationship on Django Admin (django.contrib.admin).

class Company(models.Model):
    name = models.CharField(max_length=100)
    status = models.BooleanField()
    users = models.ManyToManyField(User, related_name='company')

Right now I am able to see the User through Company on Django Admin but I cannot access the company through User.

What is the correct way to have access to reverse relationship?

like image 866
Ugo Guazelli Avatar asked Jan 21 '18 22:01

Ugo Guazelli


1 Answers

You have to use inlines in your admin pages.

in your admin.py

from __future__ import unicode_literals
from django.contrib.auth.admin import UserAdmin
from django.contrib import admin
from django.contrib.auth import get_user_model
from .models import Company

User = get_user_model()

class CompanyInline(admin.TabularInline):
    model = Company.users.through


@admin.register(User)
class MyUserAdmin(UserAdmin):
    inlines = [CompanyInline, ]


@admin.register(Company)
class CompanyAdmin(admin.ModelAdmin):
    pass

You can read more about this in docs here

There are several options available for Inlines (for example - stacked/inline, collapse, extra, min etc) you can read more about it in the docs

like image 172
at14 Avatar answered Nov 12 '22 18:11

at14