如何在 Django admin 中限制对外键的选择

How to limit choices to Foreign keys in Django admin

我 运行 在使用 Django 管理时遇到问题。我正在构建一个小型 ScrumBoard。它有项目、状态、故事和任务。

考虑以下模型:

@python_2_unicode_compatible
class Project(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        verbose_name = _('Project')
        verbose_name_plural = _('Projects')

    def __str__(self):
        return self.name

@python_2_unicode_compatible
class Status(models.Model):
    name = models.CharField(max_length=64) # e.g. Todo, In progress, Testing Done
    project = models.ForeignKey(Project)

    class Meta:
        verbose_name = _('Status')
        verbose_name_plural = _('Statuses')

    def __str__(self):
        return self.name


@python_2_unicode_compatible
class Story(models.Model):
    """Unit of work to be done for the sprint. Can consist out of smaller tasks"""
    project = models.ForeignKey(Project)
    name=models.CharField(max_length=200)
    description=models.TextField()
    status = models.ForeignKey(Status)

    class Meta:
        verbose_name = _('Story')
        verbose_name_plural = _('Stories')

    # represent a story with it's title
    def __str__(self):
        return self.name

问题:当管理员用户创建故事时,他将看到所有项目的状态,而不是一个项目的状态。

您将需要 django-smart-selects

要按项目过滤状态,您需要您的故事已经存在,以便 django 知道我们在谈论哪个项目。如果你设置状态为空,你可以这样做(意味着你保存并在第一次保存时继续设置状态)

class StatusAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        form = super(StatusAdmin, self).get_form(request, obj, **kwargs)
        if obj and obj.project:
            form.base_fields['status'].queryset = \
                form.base_fields['status'].queryset.filter(project=obj.project)
        elif obj is None and 'status' in form.base_fields: # on creation
            del form.base_fields['status']
        return form