0

I have this class in django 1.4:

class ProgramForm(forms.ModelForm):
    ...other fields...
    program_interests = forms.ModelMultipleChoiceField(
        widget=forms.Select(),
        queryset= Programs.objects.filter(is_active=True),
        required=True,
        label="Program Interest",
    )

And this works fine; the template looks like this:

{% get_fieldset other_fields,program_interests as the_fields from programform %}
{% for field in the_fields %}
        <li id="li_{{field.html_name}}">
            <label for="id_{{ field.html_name }}">{{ field.label }}</label>
            {{ field }}
        </li>
{% endfor %}

My 'Programs' model has a field for type of program. What I want to do is populate program_interests' ModelMultipleChoiceField and order them first by type of program and then alpha. Each type of program will have a label in the drop down (a disabled option). So, what I want to do is something like this:

qs1 = Programs.objects.filter(is_active=True, type=1),
qs2 = Programs.objects.filter(is_active=True, type=2),
qs3 = Programs.objects.filter(is_active=True, type=3),
queryset = qs1 | qs2 | qs3,

But this doesn't work. Any idea if I'm going about this the right way?

EDIT: what I've tried

    q1 = Q(is_active=True,type=1)
    q2 = Q(is_active=True,type=2)
    q3 = Q(is_active=True,type=3)
    program_interests = forms.ModelMultipleChoiceField(
        widget=forms.Select(),
        queryset= Programs.objects.filter(q1 | q2 | q3).order_by('type'),
        required=True,
        label="Program Interest",
    )

This could work if I can append a disabled input inbetween the q1 and q2 to use as a label. Anyone know how I would do that?

smilebomb
  • 5,123
  • 8
  • 49
  • 81
  • Set it on init, just use search: [filtering query set and setting default value as an object](http://stackoverflow.com/questions/5329586/django-modelchoicefield-filtering-query-set-and-setting-default-value-as-an-obj) – Aleksey Pastuhov Aug 26 '14 at 21:16

1 Answers1

0

You can not "or" querysets, You should or conditions and then maybe sort.

I think something like this will work:

from django.db.models import Q

q1 = Q(is_active=True, type=1)
q2 = Q(is_active=True, type=2)
q3 = Q(is_active=True, type=3)

queryset = Programs.objects.filter(q1 | q2 | q3).order_by('type')
Oberix
  • 1,131
  • 7
  • 13
  • After some experimentation I find this is no different than `queryset = Programs.objects.filter(is_active=True).order_by('type','name')`. This leaves me right where I started. Is there a way to insert disabled inputs in-between `q1` and `q2`? – smilebomb Aug 27 '14 at 14:02