Django多对多管理员通过对象自定义

时间:2014-03-05 23:36:29

标签: python django django-models django-admin

假设我有这样一个模型:

from django.db import models

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

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)

    class Meta:
        db_table = mysql_membership

所以我的中间表是由我选择(并手动创建)的。现在我想为Group对象创建带有内联formset的管理员。就像这样:

class MembershipInline(admin.TabularInline):
    model = Membership
    extra = 1

class GroupAdmin(admin.ModelAdmin):
    inlines = (MembershipInline,)

admin.site.register(Group, GroupAdmin)

问题是,当我尝试获取给定组的编辑表单时,我收到此错误:

Exception Type:     OperationalError
Exception Value:    

(1054, "Unknown column 'mysql_membership.id' in 'field list'")

这对我来说是可以理解的,因为这个mysql_membership表中的主键是一组列(而不是一个简单的primary_key列):

PRIMARY KEY (person, group, invite_reason)

我想让您知道,我无法编辑数据库架构。如何基于自定义“直通”表/模型为多对多字段启用formset?请帮忙。

顺便说一句。我正在使用以下示例: https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#working-with-many-to-many-intermediary-models

0 个答案:

没有答案