【问题标题】:Django ordered ManyToManyField in admin interfaceDjango 在管理界面中订购了 ManyToManyField
【发布时间】:2010-12-17 02:42:13
【问题描述】:

我有一个旧数据库,其中包含文档和作者表。第三个表定义了文档和作者之间的有序多对多关系,使用文档和作者的外键和一个整数来指定给定文档的作者顺序。

使用 Django 1.1.1(或 SVN),有没有办法在管理页面中编辑文档作者及其顺序?

【问题讨论】:

    标签: django django-admin


    【解决方案1】:

    这很快而且有点粗糙,但它应该能让你接近(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

    【讨论】:

    • 我之前尝试过,但在文档管理页面中只有一行/作者的条目显示供编辑,即使我在 FooInline 类中指定了 extra = 3。
    • 我刚刚测试了这个(带 1.1.1),并且可以选择在添加新文档时最初附加 3 个作者,在编辑文档时再附加 3 个作者。不知道它可能会落在哪里,但它似乎对我来说很好。
    • 出于好奇,您是否尝试使用 inspectdb 来查看您获得的模型表示形式 (docs.djangoproject.com/en/dev/ref/django-admin/#inspectdb)。
    • 好的,我已经找到了差异的原因。在我的旧数据库中,Foo 表不包含“id”主键列。相反,它在所有三列上都有键,第一个键是文档 ID,然后是作者 ID,然后是顺序。当我将 primary_key=True 放在一个字段上时,管理页面中只显示一个条目。
    • inspectdb 输出的模型类似于我的手工编码: class DocumentAuthor(models.Model): doc_id = models.IntegerField(primary_key=True) author_id = models.IntegerField(primary_key=True) order_presentation = models.IntegerField(primary_key=True) 类元:db_table = u'document_author'
    【解决方案2】:

    这也可能对您有所帮助 - there is some utility 在 Django 中为遗留数据库构建模型。

    我已经使用它为 mediawiki 数据库构建了一个模型。它使大部分事情都正确,但您需要稍微调整模型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 2013-03-17
      • 2016-05-08
      • 2015-06-11
      • 1970-01-01
      相关资源
      最近更新 更多