0

I have a many to many relationship in my models like this.

class Shift(models.Model):
    employees = models.ManyToManyField('account.Employee', 
                                       related_name='allocated_in',
                                       blank=True)

Say I have a particular instance of employee employee. I can remove him from single shift instance shift like this.

shift.employees.remove(employee)

How can I remove employee from every instance of a queryset of Shift?

shift_qs = Shift.objects.filter(date__gt=timezone.now().date)

I want to remove employee from every instance in shift_qs in a single query. Preferably without looping over queryset.

Nafees Anwar
  • 6,324
  • 2
  • 23
  • 42

1 Answers1

2

Use the intermediate model:

IModel = shift_qs.employees.through
IModel.objects.filter(shift__in=shift_qs, employee=employee).delete()
Endre Both
  • 5,540
  • 1
  • 26
  • 31