I have a table for ManyToMany relationship. Where each Tutor need to input multiple days that he wants to tutor student. Like:
Availability Tutor:
user available_day time
t1 Sun 6,7,8
t2 mon 3,4
t1 mon 1,2
I would like to get all tutor where availablity is based on search day.
Model:
class TutorProfile(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
tutor_availablility = models.ManyToManyField(
Day)
queryset:
def get_queryset(self):
subject_param = self.request.GET.get('subject')
bookday = self.request.GET.get('book_day')
grade = self.request.GET.get('grade')
li = list(bookday.split(","))
print("Book Info:", li)
for i in range(len(li)):
print(li[i])
_day_name = datetime.strptime(li[i], "%d-%m-%Y").strftime("%A")
print("Day Name:", _day_name)
day_num = Day.objects.get(day_name=_day_name)
print("Day_Num",day_num)
result = TutorProfile.objects.filter(
tutor_availablility=day_num).all()
return result
When I run this query it only loop over one time for one day but not for multiple days.
Now how may I run this query so that it will not stop after one loop.
After One loop it says: An exception occurred An exception occurred
I tried to apply try catch block here. But getting no clue. Why stop loop after one cycle?
CodePudding user response:
After one loop, you are returning the results. Instead, use the Q object to store the conditions and then filter the queryset outside of the for loop:
from django.db.models import Q
...
query = Q()
for i in range(len(li)):
_day_name = datetime.strptime(li[i], "%d-%m-%Y").strftime("%A")
day_num = Day.objects.get(day_name=_day_name)
qeury = query | Q(
tutor_availablility=day_num)
return TutorProfile.objects.filter(query)
Update
Although the following code should not change the outcome, but try like this:
li = list(bookday.split(","))
query = list(map(lambda x: datetime.strptime(x, "%d-%m-%Y").strftime("%A"), li)
return TutorProfile.objects.filter(tutor_availability__day_name__in = query)