更改模型字段的选择属性 [英] Change choices attribute of model's field

查看:173
本文介绍了更改模型字段的选择属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题类似于在运行时设置模型字段选择属性? 但是,我的问题是我想在类级别更改choices属性的默认值.

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.

我有这个

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

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

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.

我尝试直接篡改RecordForm的 init :

I tried tampering directly with the init of the RecordForm:

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

或记录的 init :

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

但似乎没有任何作用.

感谢您的帮助.

推荐答案

我刚发现:

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

在RecordForm的 init 中也可以做到这一点.但是@Peter DeGlopper在评论中的答案更好.

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

这篇关于更改模型字段的选择属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆