Django管理GenericForeignKey小部件

时间:2011-07-20 03:39:27

标签: django django-admin django-widget

我正在创建一个Django应用程序,其中所有模型可以按照用户设置的顺序相互关联。我正在使用GenericForeignKeys设置所有这些。踢球者是我需要能够支持这些类型的关系/管理员的多个集合。因此,一个对象可以有一个以上的相关对象集合。

有没有人知道这种情况下一个好的GenericForeignKey小部件?最好是填充管理表单的自动填充搜索,因为我最终可能会有大量的对象。

这是我的应用程序的代码,可以更好地了解我的意思。

from django.contrib import admin
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django import forms


# Models
class Base(models.Model):
    title = models.CharField(max_length=255)

    class Meta:
        abstract = True

    def __unicode__(self):
        return self.title

class Related(Base):
    """ A generic relationship model for relating resources.
    """
    order = models.IntegerField(blank=True, null=True)
    limit = models.Q(model = 'Apple') | models.Q(model = 'Orange') | models.Q(model = 'Pear') 

    content_type = models.ForeignKey(ContentType, related_name="related_%(class)s")
    object_id = models.PositiveIntegerField(db_index=True)
    object = generic.GenericForeignKey()

    related_content_type = models.ForeignKey(ContentType, related_name="related_related_%(class)s", limit_choices_to = limit)
    related_object_id = models.PositiveIntegerField(db_index=True)
    related_object = generic.GenericForeignKey('related_content_type', 'related_object_id')

    class Meta:
        ordering = ('order',)
        abstract = True

    def __unicode__(self):
        return self.object.title

class FreshFruit(Related):
    pass

class OldFruit(Related):
    pass

class Apple(Base):
    pass

class Orange(Base):
    pass

class Pear(Base):
    pass

# Admin classes
class FreshFruitInline(generic.GenericStackedInline):
    model = FreshFruit
    extra = 1
    # Admin classes

class OldFruitInline(generic.GenericStackedInline):
    model = OldFruit
    extra = 1

class AppleAdmin(admin.ModelAdmin):
    inlines = [FreshFruitInline, OldFruitInline,]
admin.site.register(Apple, AppleAdmin)

class OrangeAdmin(admin.ModelAdmin):
    inlines = [FreshFruitInline, OldFruitInline,]
admin.site.register(Orange, OrangeAdmin)

class PearAdmin(admin.ModelAdmin):
    inlines = [FreshFruitInline, OldFruitInline,]
admin.site.register(Pear, PearAdmin)

我进行了搜索和搜索,并找到了为ManyToMany关系执行此操作的小部件,但对我的情况没有任何帮助。

感谢您抽出时间来研究这个问题。

1 个答案:

答案 0 :(得分:7)

看看Grappelli的通用外键小部件,效果很好: django-grappelli/generic_2_2