简体   繁体   中英

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 = [ 'printable_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 (eg 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?

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

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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