Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ordered ManyToManyField in admin interface

I have a legacy database with tables for documents and authors. A third table defines an ordered many to many relationship between the documents and authors, using foreign keys to the documents and the authors and an integer to specify the author order for a given document.

Using Django 1.1.1 (or SVN), is there a way to edit the document authors and their order in an admin page?

like image 225
Luís Marques Avatar asked Feb 05 '26 06:02

Luís Marques


1 Answers

This is quick and a bit rough, but it should get you close(r).

from django.db import models
from django.contrib import admin

class Document(models.Model):
    name = models.CharField(max_length = 128)

    def __unicode__(self):
        return self.name

class Author(models.Model):
    name = models.CharField(max_length = 128)
    document = models.ManyToManyField(Document, through = 'Foo')

    def __unicode__(self):
        return self.name

class Foo(models.Model):
    document = models.ForeignKey(Document)
    author = models.ForeignKey(Author)
    author_order = models.IntegerField()

class FooInline(admin.TabularInline):
    model = Foo

class DocumentAdmin(admin.ModelAdmin):
    inlines = [ FooInline ]

admin.site.register(Author)
admin.site.register(Document, DocumentAdmin)

http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany http://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects

like image 90
Jason Leveille Avatar answered Feb 09 '26 08:02

Jason Leveille