Search code examples
pythondjangofiltermany-to-many

Django filter a day name in many to many field that contains list of days


class DayOfWeek(models.Model):
    name = models.CharField(max_length=45)


class PermanentShiftSchedule(models.Model):
    id = models.UUIDField(primary_key=True, editable=False, default=uuid4)
    shift = models.ForeignKey(Shift,  related_name='shift_permanent_schedule', on_delete=models.CASCADE)
    branch_employee = models.ForeignKey(BranchEmployee, related_name='branch_emp_permanent_schedule',
                                    on_delete=models.CASCADE)
    days_of_week = models.ManyToManyField(DayOfWeek, related_name='permanent_shift_days')

Now I want to filter the PermanentShiftSchedule where days_of_week field contanins "Thursday"

days_of_week field may contain multiple days names


Solution

  • You can try filter by related use double underscore __

    PermanentShiftSchedule.objects.filter(days_of_week__name__icontains="Thursday")