碰巧我需要将ManytoMany字段显示为CheckboxSelectMultiple,没问题。技巧部分是要显示默认字段,用户应该能够添加新选项,此选项应显示在表单上。
这是我做的:
models.py
class Feature(models.Model):
name = models.CharField( _("Feature Name"), max_length=40)
default = models.BooleanField(_("Is Global Feature"), default = False)
class SomeModel(models.Model):
features = models.ManyToManyField(Feature, related_name='features')
forms.py
class FeatureForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
somemodel = kwargs['somemodel']
kwargs.pop('somemodel')
super(SpaFeatureForm, self).__init__(*args, **kwargs)
default_features = Feature.objects.filter(default=True)
custom_features = somemodel.features.filter(default=False)
q_set = QuerySetChain(default_features, custom_features)
self.fields['features'].widget = forms.CheckboxSelectMultiple()
self.fields['features'].queryset = q_set
class Meta:
model = m.Spa
fields = ('features',)
我仍然会实现第二部分,它将是一个功能表单和某些js来填充Checkbox Multiselect字段选项。
我修改了@akaihola answer如何链接查询集,将def _all更改为def all。它运作良好。
现在的问题是:这是最好的解决方案吗?