繁体   English   中英

如何在初始化时从同一 Model 中调用 static function? DJANGO PYTHON

[英]How to call call a static function from the same Model in the Model upon initialisation? DJANGO PYTHON

So long story short, I have a Car model and a CarVersion model and I want the user to have the ability to choose from the availble car versions saved in the database, through a html select field.

我无法理解如何从 CarVersion model 动态生成选择字段。 我有 function,但我不能在汽车 model 内调用它。

这是我到目前为止的代码:

class Car(models.Model):
    choices = get_choices()

    name = models.CharField(max_length=50, unique=True)
    version = models.ForeignKey(CarVersion, choices=get_choices(), on_delete=models.RESTRICT)
    
    @staticmethod
    def get_choices():
        options = CarVersion.objects.all().values_list("pk", "name")
        try:
            if not options:
                return [(0, "No versions in database. Call your administrator.")]
        except ProgrammingError:
            return [(0, "No versions in database. Call your administrator.")]
        return [(1, "Test")]

我想调用 function get_choices

version = models.ForeignKey(CarVersion, choices=get_choices(), on_delete=models.RESTRICT)但我不知道该怎么做,而 function 被声明为 model。 如果我在 model 之外定义它,它可以工作,但肯定有更好的方法,而不是用一堆 model 特定功能弄乱我的 models.py 文件。

PS get_choices还没有完成,但只要我能调用它,我就会处理它。

出于几个原因,我建议不要这样做。 model 字段上的choices参数用于验证您可能添加到数据库中的数据。

除此之外,你写它的方式,在加载模块时调用获取CarVersion对象的 function 。 这是一个坏主意。 当您甚至还没有数据库连接时,您可能希望在某个地方导入模块。

由于您的意图是为用户生成 HTML 形式的选项,因此正确的方法是依赖 Django Forms 的外键功能。 ModelChoiceField应该已经完成了您需要的操作。

PS:事实上,当您从具有ForeignKey字段的ModelForm创建 ModelForm 时,会自动实例化ModelChoiceField 请参阅ModelForm页面上的字段转换列表。

我要感谢 Daniil 的贡献,如果没有它,我将永远无法针对我的问题提出正确的问题,即:

如何动态生成选择字段。

可以在以下位置找到该问题的答案: 如何创建动态 Django 选择字段

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM