1

我在 Django 1.5 中有一个自引用模型,如下所示:

RELATIONSHIP_PARENT = 1
RELATIONSHIP_BLOCKED = 2
RELATIONSHIP_STATUSES = (
    (RELATIONSHIP_PARENT, 'Parent'),
    (RELATIONSHIP_BLOCKED, 'Blocked'),
) 

class Message(models.Model):
    content = models.CharField("Content", max_length=160, db_index=True)
    relationships = models.ManyToManyField('self',
        through='Relationship',
        symmetrical=False,
        related_name='related_to')

class Relationship(models.Model):
    parent_message = models.ForeignKey(Message, related_name='parent_messages')
    child_message = models.ForeignKey(Message, related_name='child_messages')
    status = models.IntegerField(choices=RELATIONSHIP_STATUSES)

我将 Django admin 配置Relationships为在查看单个Message面板时显示为内联,如下所示:

from django.contrib import admin
from demo.models import Message, Relationship

class RelationshipInline(admin.TabularInline):
    model = Relationship
    extra = 0
    fk_name = 'parent_message'

class MessageAdmin(admin.ModelAdmin):
    inlines = (RelationshipInline,)

admin.site.register(Message, MessageAdmin)
admin.site.register(Relationship)

我打算在表中存储许多消息(其中有很多父子连接)。每当我通过管理面板查看单个消息时,我都会看到如下内容:

在此处输入图像描述

如红圈所示,Django admin 收集数据库中的所有消息,并在菜单中显示为下拉列表。我已经阅读了一些防止它的方法,我发现最接近的是在管理面板中表示多对多关系,但是当我尝试raw_id_fields = ('parent_message', )RelationshipInline课时,它似乎没有做任何事情。

如果有人可以向我推荐一个链接或资源,或者只是向我展示如何阻止 Django 显示下拉列表中的每个条目/消息,我将非常感谢您的帮助。谢谢你。

4

2 回答 2

2

这应该有效。

class RelationshipFormSet(BaseInlineFormSet):
    def get_queryset(self):
        if not hasattr(self, '_queryset'):
            criteria = {} #Your criteria here
            qs = super(RelationshipFormSet, self).get_queryset().filter(**criteria)
            self._queryset = qs
        return self._queryset

class RelationshipInline(admin.TabularInline):
    model = Relationship
    extra = 0
    fk_name = 'parent_message'
    formset =  RelationshipFormSet
于 2013-06-21T18:54:42.817 回答
2

raw_id_fields应该进入管理类:

管理员.py

class MessageAdmin(admin.ModelAdmin):
    inlines = (RelationshipInline,)
    raw_id_fields = ('parent_message', )
于 2019-09-19T10:15:45.380 回答