vendredi 8 octobre 2021

The one line if else elif not working in Django

After referring to this answer Tim Pietzcker, I implemented that code on my website. I'm not getting the proper solution for the same.

Well, I try to implement if elif and else statement in one line Django. So I have tried this.

views.py

cart1 = CartTube.objects.values_list('tube__tubecode', flat = True)
cart2 = CartDrum.objects.values_list('drum__drumcode', flat = True)

machine = Machine.objects.filter(tubecode__in=cart1) if cart1 else Machine.objects.filter(drumcode__in=cart2) if cart2 else Machine.objects.filter(Q(tubecode__in=cart1) & Q(drumcode__in=cart2)) if cart1 else Machine.objects.all().order_by('id')

In the above code this part Machine.objects.filter(Q(tubecode__in=cart1) & Q(drumcode__in=cart2)) if cart1 is not working

Well, From the above code I'm trying to find a solution:

  1. If the user chooses Drum as a product then the same code should match with Machine and filter the exact matching product. and if,
  2. Drum product + Tube product is chosen then show the exact combination product from the Machine

Since the individual code works perfectly. Down below are the code work perfectly.

   ✔️ machine = Machine.objects.filter(tubecode__in=cart1)if cart1 else Machine.objects.all().order_by('id') 
   ✔️ machine = Machine.objects.filter(drumcode__in=cart2) if cart2 else Machine.objects.all().order_by('id') 
   ✔️ machine = Machine.objects.filter(Q(tubecode__in=cart1) & Q(drumcode__in=cart2)) if cart1 else Machine.objects.all().order_by('id')

Tell me where I'm going wrong

Aucun commentaire:

Enregistrer un commentaire