簡體   English   中英

用於ModelChoiceField的Django表單QuerySet

[英]Django form QuerySet for ModelChoiceField

我有一個表格,正在使用以下字段。

contact_country = forms.ModelChoiceField(queryset=Country.objects.all())

國家模型看起來像這樣

class Country(models.Model):
    iso = models.CharField(max_length=2)
    name = models.CharField(max_length=80)
    printable_name = models.CharField(max_length=80)
    iso3 = models.CharField(max_length=3,null=True, blank=True)
    numcode = models.IntegerField(null=True, blank=True)
    special = models.BooleanField(default=False)

    def __unicode__(self):  
        return self.printable_name

    class Meta:
        ordering = [ 'printable_name' ]

“特殊”字段表示該國家為“特殊”。 如果該國家/地區是“特殊”國家/地區,我希望它出現在列表的其余部分之前-我相信您已經在網上看到過其他地方(例如,英語國家(如澳大利亞,英國和美國)位於頂部)選擇,但也會與其他國家/地區一起使用)。

QuerySet有可能嗎? 還是我應該在別處尋找?

contact_country = forms.ModelChoiceField(queryset=Country.objects.order_by('special'))有效?

這未經測試,因此您可以嘗試一下,但可能無法滿足您的要求。

您認為這樣做:

specials = Country.objects.filter(special=True)
all_of = Country.objects.all()

# worst thing is, this is a list, not a queryset...
new_list = list(specials)+list(all_of)

# add new object to you form...
YourForm.base_fields['contact_country'] = forms.ChoiceField(choices=[(x.id,x) for x in new_list])

您的障礙是,使用列表而不是直接從queryset創建列表

這將以骯臟的方式解決您的問題,但這是我在modelform無法幫助您時使用的解決方案...

您可以覆蓋默認順序

class Meta:
    ordering = [ '-special', 'printable_name' ]

您還可以編寫一個自定義管理器,但這不值得...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM