Home > Software design >  Django: how to use "or" in django filter method?
Django: how to use "or" in django filter method?

Time:04-23

i want to filter a model by a tuple, i dont know if that is the right sentence to use but i have a model that looks like this

USER_COURSE_RATING = (
        ("1.0", "1.0 - Poor"),
        ("2.0", "2.0 - Fair"),
        ("3.0", "3.0 - Good"),
        ("4.0", "4.0 - Amazing"),
        ("5.0", "5.0 - Excellent"),
)

class Course(models.Model):
    course_title = models.CharField(max_length=10000)

class CourseRating(models.Model):
    course = models.ForeignKey(Course, on_delete=models.CASCADE)
    rating = models.CharField(max_length=1000, choices=USER_COURSE_RATING, null=True, blank=True)

and what i want to do in the views if to filter the CourseRating by the tuple i defined above called USER_COURSE_RATING

i have written the view but it seems not to be working, NOTE: i am not getting any error message but it not working

def course_detail(request, course_slug):
   rating_count = CourseRating.objects.filter(course=course, rating="3.0" or "4.0" or "5.0").count()

So i want to only display the count if the rating was either 3.0, 4.0 or 5.0 that is what i am expecting

CodePudding user response:

You can test if a specific column has one of multiple values using in.

For example:

tbl.objects.filter(course=course, rating__in=["3.0","4.0","5.0"])

This is analogous to the equivalent membership test feature in Python:

rating = "3.0"
if rating in ["3.0", "4.0", "5.0"]:
    print("Yes")
  • Related