There are two signs with FK in one of them.

parent:

+----+---------+ | Id | Name | +----+---------+ | 1 | Test #1 | | 2 | Test #2 | | 3 | Test #3 | +----+---------+ 

subsidiary:

 +----+---------+-----------+ | Id | Traffic | parent_id | +----+---------+-----------+ | 1 | 1000 | 1 | | 2 | 2000 | 3 | +----+---------+-----------+ 

I need to do a queryset for the form and connect them by key. On sql something similar to the query:

 select p.parent_id, p.traffic, c.name from child c, parent p where c.parent_id = p.id 

The form:

 class NewForm(forms.Form): query = Child.objects.all().... selectbox = forms.ModelChoiceField(queryset=query, required=True, initial=0, widget=forms.Select, label=_(u'Select field')) class Meta: fields = [ 'selectbox', ] 

Is there any easy way to do this?

  • Found that can be arranged in the following way: query = Child.objects.all (). Values_list ('id', 'parent__name'). This gives the two required fields, but the output to the template is not as it should be. Returns "option value =" (1L, u'Test # 1 ') "> (1L, u'Test # 1') </ option", instead of "option value =" 1 "> Test # 1 </ option". How to get a normal result has not yet found. - johndark

1 answer 1

In general, it turned out to find such a solution (thanks to the people with the pyha forum)

 def get_server_list(): return Child.objects.all().values_list('parent_id', 'parent__name') class NewForm(forms.Form): selectbox = forms.Field(required=True, widget=forms.Select, label=_(u'Select field')) class Meta: fields = [ 'selectbox', ] def __init__(self, *args, **kwargs): kwargs.setdefault('label_suffix', '') super(NewForm, self).__init__(*args, **kwargs) self.fields['selectbox'] = \ forms.ChoiceField(choices= [(o[0], str(o[1])) for o in get_server_list()], initial=1 ) 

Now you can use the selectbox field in a template like:

 {% render_field form.selectbox class="form-control required" %} 

and get a reasonable selection code on the page:

 <select class="form-control required" name="selectbox"> <option value="1">Test #1</option> <option value="3">Test #3</option> </select> 

Not sure that this is the best way, but in any case it works as I need.