开发者

Django form QuerySet for ModelChoiceField

I've got a Form which I'm using the following field in.

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

The Country model looks like this

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 = [ 'printabl开发者_StackOverflowe_name' ]

The 'special' field indicates that the country is "special". If the country is "special" I want it to appear before the rest of the listing - as I'm sure you've seen elsewhere on the web (e.g. English speaking countries like Australia, United Kingdom and United States at the top of the select, but also again with the rest of the countries).

Is that possible with QuerySet? Or should I be looking elsewhere?


Does contact_country = forms.ModelChoiceField(queryset=Country.objects.order_by('special')) work?


This is untested, so you may give it a try, but it may not give it what you want...

in your view do this:

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])

Your handicap is, yo create the list using a list, not directly from queryset

This will solve your pronblem, with a dirty looking way, but it is a solution i used when modelform can not help you...


You can override the default ordering:

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

You can also write a custom manager but it doesn't worth...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜