Quinnyboy
Quinnyboy

Reputation: 13

How could I shorten this django view request?

def test(request):
    x1 = MenuItem.objects.filter(item_category__icontains='PANCAKE')
    x2 = MenuItem.objects.filter(item_category__icontains='EGG')
    x3 = MenuItem.objects.filter(item_category__icontains='PANNIS')
    x4 = MenuItem.objects.filter(item_category__icontains='SUBS')
    x5 = MenuItem.objects.filter(item_category__icontains='WRAPS')
    x6 = MenuItem.objects.filter(item_category__icontains='TEA')
    x7 = MenuItem.objects.filter(item_category__icontains='FRAPPE')
    x8 = MenuItem.objects.filter(item_category__icontains='SMOOTHIE')
    x9 = MenuItem.objects.filter(item_category__icontains='GLUTENF')
    x10 =MenuItem.objects.filter(item_category__icontains='WAFFLES')
    x11 =MenuItem.objects.filter(item_category__icontains='TOAST')
    x12 =MenuItem.objects.filter(item_category__icontains='HOTPASTA')
    x13 =MenuItem.objects.filter(item_category__icontains='BAGELS')
    x14 =MenuItem.objects.filter(item_category__icontains='FRIES')
    x15 =MenuItem.objects.filter(item_category__icontains='SALADS')
    x16 =MenuItem.objects.filter(item_category__icontains='DESSERTS')
    context={
        'p':x1,
        'e':x2,
        'pn':x3,
        's':x4,
        'w':x5,
        't':x6,
        'f':x7,
        'sm':x8,
        'gf':x9,
        'wa':x10,
        'to':x11,
        'hp':x12,
        'b':x13,
        'fr':x14,
        'sa':x15,
        'd':x16,

    }
    return render(request, 'posts/test.html',context)

I know there are many different ways to shorten this but i was considering taking suggestions on how would someone who's proficient in python frameworks would handle this

Upvotes: 1

Views: 53

Answers (1)

Jrog
Jrog

Reputation: 1527

Python's for ... in ... loop statement and dictionary makes it simple to shorten the code. Also, when a new value is added in the future, simply enter the key: value in data_dict

def test(request):
    data_dict = {
        'p': 'PANCAKE',
        'e': 'EGG',
        'pn': 'PANNIS',
        's': 'SUBS',
        'w': 'WRAPS',
        't': 'TEA',
        'f': 'FRAPPE',
        'sm': 'SMOOTHIE',
        'gf': 'GLUTENF',
        'wa': 'WAFFLES',
        'to': 'TOAST',
        'hp': 'HOTPASTA',
        'b': 'BAGELS',
        'fr': 'FRIES',
        'sa': 'SALADS',
        'd': 'DESSERTS',
    }
    context = {}

    for key, value in data_dict.items():
        context[key] = MenuItem.objects.filter(item_category__icontains=value)

    return render(request, 'posts/test.html', context)

Upvotes: 1

Related Questions