Change choices attribute of model's field

淺唱寂寞╮ 提交于 2020-01-03 04:46:10

问题


This question is similar to Set model field choices attribute at run time? However, my problem is that I want to change the default value of the choices attribute, at class level.

I have this

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

My problem is that all the RecordForm will be created with a TypedChoiceField using the available choices that were in the model at the time of the module import. However, users can create more projects, and those will never appear in the RecordForm; same for deletion.

I tried tampering directly with the init of the RecordForm:

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

or with the init of the Record:

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

but nothing seems to work.

Thanks for your help.


回答1:


I just figured out that:

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

In the init of the RecordForm also does the trick. But @Peter DeGlopper answer in the comments is better.



来源:https://stackoverflow.com/questions/20156162/change-choices-attribute-of-models-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!