簡體   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