更改模型字段的选择属性

时间:2013-11-22 23:05:53

标签: python django oop django-models django-forms

此问题与Set model field choices attribute at run time?类似 但是,我的问题是我想在类级别更改choices属性的默认值。

我有这个

class Project(models.Model):

    name = models.CharField(...)

    @staticmethod
    def getAllProjectsTuple():
        return tuple([(p.id, p.name) for p in Project.objects.all()])

class Record(models.Model):

      project = models.ForeignKey(
                            Project,
                            verbose_name='Project',
                            help_text='Project name',
                            blank=True, null=True,
                            on_delete=models.SET_NULL,
                            choices = Project.getAllProjectsTuple(),

class RecordForm(ModelForm):

       class Meta:
              model = Record

我的问题是,所有RecordForm都将使用TypedChoiceField创建,使用模块导入时模型中的可用选项。但是,用户可以创建更多项目,而这些项目永远不会出现在RecordForm中;同样的删除。

我尝试直接使用RecordForm的 init 进行篡改:

self.fields['project']._choices = [('', '---------'),] + [(p.id, p.name) for p in Project.objects.all()]

或使用记录的 init

self._meta.get_field('project')._choices = Project.getAllProjectsTuple()

但似乎没有任何效果。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我刚才发现:

self.fields['project'].choices = [('', '----------')] + [(p.id, p.name) for p in Project.objects.all()]

在RecordForm的 init 中也有诀窍。但@Peter DeGlopper在评论中的回答更好。

相关问题