G
G
Gasoid2014-10-03 13:56:54
Django
Gasoid, 2014-10-03 13:56:54

How to filter by form like this in django orm?

There is a model with fields

class Order(models.Model):
    o1 = models.BooleanField()
    o2 = models.BooleanField()
    o3 = models.BooleanField()
    o4 = models.BooleanField()
    o5 = models.BooleanField()
    # и т.д.

there is a form based on the model
class OrderForm(form.ModelForm):
    class Meta:
        model = Order

o1-on are checkboxes, i.e. some of them are True and some are False
How to filter order in this case from the form and in general.
Order.objects.filter(o1=form.cleaned_data['o1'], o2=form.cleaned_data['o2'])
# но тогда получим, что в каком то может быть o1=True, но o2=False и орм ничего не найдет.

Order.objects.filter(Q(o1=form.cleaned_data['o1']) | Q(o2=form.cleaned_data['o2']))
#получим что  при o1=False мы не найдем

пока в голову ничего не пришло, мож кто подскажет?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Swasher, 2014-10-09
@Swasher

Roughly something like this:

myquery &= Q(o1__exact=form.cleaned_data['o1'])
myquery &= Q(o2__exact=form.cleaned_data['o2'])
myquery &= Q(o3__exact=form.cleaned_data['o3'])
table = Order.objects.filter(myquery)

I'm not sure about applying __exact to a boolean field, but the essence seems to be clear, you'll finish it.

A
Alexey Bukin, 2014-10-12
@abukin

Apparently you need to check for the presence of a positive value in the field.
Here's an option for you:

Order.objects.filter(**{k: v for k, v in form.cleaned_data.items() if k.startswith('o') and int(v)})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question