Home > Enterprise >  Apply method within a django queryset?
Apply method within a django queryset?

Time:05-04

I have a Django queryset that returns all the staff called 'bob' working in all my restaurants. It does this successfully:

restaurant_staff = Restaurant.objects.filter(staff__staff_name="bob")

However, the Staff model has a method that returns only staff that were employed on a given date that I would like to use. Essentially I want all the bobs who are working on today. I've tried adding the method .valid_on_certain_date(self, date.today()) onto the query but it uses the Restaurant classes valid_on_certain_date not the Staff class's valid_on_certain_date method:

restaurant_staff = Restaurant.objects.filter(staff__staff_name="bob").valid_on_certain_date(self, date.today())

A simplified version of my models.py:

class Restaurant(models.Model):
    restaurant_name = models.CharField(max_length=30)
    restaurant_dates_open = DateRangeField()


class Staff(models.Model):
    staff_name = models.CharField(max_length=30)
    restaurant = models.ForeignKey(Restaurant)
    employment_dates = DateRangeField()


My querysets.py:

class ValidityQuerySet(QuerySet):
    def valid_on_certain_date(self, date):
        return  self.filter(restaurant_dates_open__contains=date)

My question is, how can I filter the Staff class by valid_on_certain_date in the Restaurant.objects.filter(staff__staff_name="bob") query?

CodePudding user response:

Note that you won't ever get a StaffQuerySet from the Restaurant model. You can at best get the ids of the staff by using restaurant_qs.values_list('staff__id', flat=True).

To get a qs of Staff, you'll have to first get the restaurant ids and then call the Staff model:

restaurant_ids = Restaurant.objects.values_list('id', flat=True)  # filter the restaurants more here
staff = Staff.objects.filter(
    staff_name='bob',
    restaurant__id__in=your_restaurant_ids
).valid_on_certain_date(date)

CodePudding user response:

Extending Queryset won't work by itself because Django doesn't know about your custom subclass. I think what you need is a custom manager. You probably don't need the Queryset subclass at all.

  • Related