Alex Rivera | Logout

How to add bi-directional manytomanyfields in django admin?

Asked 2009-08-27T07:31:08.323
11

In my models.py i have something like:

class LocationGroup(models.Model):
    name = models.CharField(max_length=200)

class Report(models.Model):
    name = models.CharField(max_length=200)
    locationgroups = models.ManyToManyField(LocationGroup)

admin.py (standard):

admin.site.register(LocationGroup)
admin.site.register(Report)

When I enter the admin page for Report, it shows a nice multiple choice field. How can I add the same multiple choice field in LocationGroup? I can access all Reports by calling LocationGroup.report_set.all()

Edit
Report

1 Answer

8

The workaround I found was to follow the instructions for ManyToManyFields with intermediary models. Even though you're not using the 'through' model feature, just pretend as if you were and create a stub model with the necessary ForeignKey.

# models:  make sure the naming convention matches what ManyToManyField would create
class Report_LocationGroups(models.Model):
    locationgroup = models.ForeignKey(LocationGroup)
    report = models.ForeignKey(Report)

# admin
class ReportInline(admin.TabularInline):
    model = models.Report_LocationGroups

class LocationGroupAdmin(admin.ModelAdmin):
    inlines = ReportInline,
answered 2009-09-20T22:29:06.127

Your Answer