Reputation: 1990
I have a view that allows you to search courses and shows you the profile/s(which in turn belong to a user) that have taken those courses. The search is working just fine but the problem is that it's not filtering based on the user_id.
models.py
class EmployeeProfile(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
first_name = models.CharField(max_length=30)
middle_name = models.CharField(max_length=30, null=True, blank=True)
last_name = models.CharField(max_length=30)
def __str__(self):
return self.first_name + ' ' + self.last_name
class SafetyCourse(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
name = models.CharField(max_length=128, unique=True)
def __str__(self):
return self.name
class SafetyCoursesTaken(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
profile = models.ForeignKey(EmployeeProfile, on_delete=models.CASCADE)
course = models.ForeignKey(SafetyCourse, on_delete=models.CASCADE)
conducted_date = models.DateTimeField(null=True, blank=True)
expiration_date = models.DateTimeField(null=True, blank=True)
class Meta:
verbose_name_plural = 'Safety Courses Taken'
Views.py
class CourseSearchView(LoginRequiredMixin, SuccessMessageMixin, generic.ListView):
login_url = reverse_lazy('users:login')
template_name = 'ppm/forms/search-courses.html'
def get_queryset(self):
pk = self.kwargs['pk']
query = self.request.GET.get('q')
# verify proper foreign key is being passed
print(pk)
if query:
# for lookups that span relationships go here: https://docs.djangoproject.com/en/1.9/topics/db/queries/
return SafetyCoursesTaken.objects.filter(Q(course__user_id=pk) & Q(course__name__icontains=query))
Now, I have checked whether the right foreign key is being passed, and it is but for one user it displays all the courses, and for the second user, it displays no courses.
I've tried many different filter variations but not have worked:
SafetyCoursesTaken.objects.filter(Q(course__user_id=pk) & Q(course__name__icontains=query))
SafetyCoursesTaken.objects.filter(Q(course__name__icontains=query),
user_id=pk)
SafetyCoursesTaken.objects.filter(Q(course__name__icontains=query)).filter(user_id=pk)
SafetyCoursesTaken.objects.filter(user_id=pk).filter(Q(course__name__icontains=query))
But none of these have worked. What am I missing?
NOTE: The query I'm passing is "10 Hour", and I'm getting the foreign key from the URL via kwargs. As previously mentioned. The search is working and getting the correct data, it's just that it's not filtering the data based on the id being sent, it's just giving me all the data.
Upvotes: 0
Views: 548
Reputation: 1990
I figured it out. When I added the specific course, it was adding the course to the wrong user because I was using self.request.user instead of grabbing the id from the URL via self.kwargs['pk'].
Sorry to have wasted anyone's time.
Upvotes: 1