I have a lot of if statements to make (based on combinations returned) and need a way for it to be done programmatically since there are so many.
Code to get every combination of ['name_query','min_views_query','max_views_query','min_date_query', 'max_date_query', 'expertise_query', 'subject_query', 'membership_query', 'sort_query'] containing 'sort_query':
def combs(x):
return [c for i in range(len(x)+1) for c in combinations(x,i) if 'sort_query' in c]
for x in combs(['name_query','min_views_query','max_views_query','min_date_query', 'max_date_query', 'expertise_query', 'subject_query', 'membership_query', 'sort_query']):
print(x)
Here are all of the array elements and their corresponding if statements each separately ("qs =" is common for every single one):
if name_query:
qs = qs.filter(name__icontains=name_query)
if min_views_query:
qs = Course.objects.annotate(Sum("lesson__views")).filter(lesson__views__sum__gte=min_views_query)
if max_views_query:
qs = Course.objects.annotate(Sum("lesson__views")).filter(lesson__views__sum__lte=max_views_query)
if min_date_query:
qs = qs.filter(date__gte=min_date_query)
if max_date_query:
qs = qs.filter(date__lte=max_date_query)
if expertise_query:
qs = qs.filter(expertise=expertise_query)
if subject_query:
qs = qs.filter(subject__name=subject_query)
if membership_query:
qs = qs.filter(allowed_memberships__membership_type=membership_query)
if sort_query == "duration":
qs = Course.objects.annotate(foobar=Sum("lesson__duration")).order_by("foobar")
Example combination result:
('name_query', 'min_views_query', 'max_views_query', 'min_date_query', 'max_date_query', 'expertise_query', 'subject_query', 'membership_query', 'sort_query')
Desired Output:
if sort_query == "duration" and membership_query and subject_query and expertise_query and max_date_query and min_date_query and min_views_query and max_views_query and name_query:
qs = Course.objects.annotate(foobar=Sum("lesson__duration")).order_by("foobar") and qs.filter(allowed_memberships__membership_type=membership_query) and qs.filter(subject__name=subject_query) and qs.filter(expertise=expertise_query) and qs.filter(date__lte=max_date_query) and qs.filter(date__gte=min_date_query) and Course.objects.annotate(Sum("lesson__views")).filter(lesson__views__sum__gte=min_views_query) and Course.objects.annotate(Sum("lesson__views")).filter(lesson__views__sum__lte=max_views_query) and qs.filter(name__icontains=name_query)
For every combination result (256 results in this case), I will need to do one if statement for each of the 256 results "anding" each of the array element names (with the exception of (sort_query == "duration")), then inside of the if statement, "anding" all of the associated queries for those array element names to make one if statement for each of the 256 combinations.
How would you do that?
Aucun commentaire:
Enregistrer un commentaire