使用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
问题:当管理员用户创建故事时,他会看到所有项目的状态,而不是一个项目的状态。
答案 0 :(得分:2)
要按项目过滤状态,您需要已经存在您的故事,因此django知道我们正在谈论的项目。如果您将状态设置为nullalble,则可以这样做(暗示,您先保存并继续保存以设置状态)
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
答案 1 :(得分:0)