Use a method other than __unicode__ in Django ModelChoiceField

I am working on some forms in Django. One field is the ForeignKey in the model, represented as ModelChoiceField in the form. ModelChoiceField currently uses the __unicode__ method of the model to populate the list, which is not my desired behavior. I would like to be able to use a different model method. From the docs, it looks like I can force my own QuerySet , but I don't see how this will help me use a method other than __unicode__ .

I would prefer to avoid divorcing this method by default, if at all possible.

Any suggestions?

+6
source share
2 answers

Not so much a user request, but also converting your request into a list. If you just do choices=some_queryset Django makes a choice of the form:

 (item.pk, item.__unicode__()) 

So do it yourself with the list:

 choices=[(item.pk, item.some_other_method()) for item in some_queryset] 
+1
source

You can override label_from_instance to specify a different method:

 from django.forms.models import ModelChoiceField class MyModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return obj.my_custom_method() 

Then you can use this field in your form. This method is intended to be overridden in subclasses. Here is the source source in django.forms.models :

 # this method will be used to create object labels by the QuerySetIterator. # Override it to customize the label. def label_from_instance(self, obj): """ This method is used to convert objects into strings; it used to generate the labels for the choices presented by this object. Subclasses can override this method to customize the display of the choices. """ return smart_unicode(obj) 
+10
source

Source: https://habr.com/ru/post/920241/


All Articles