I'm using Django REST Framework to implement an associative schedule system, where a user can subscribe to an association and receive its events. Each association can have many groups (you choose yours when you subscribe to the association), so that the events are often the same for each group but with different places and dates.
The model looks like this :
class Association(models.Model):
name = models.CharField(max_length=40, blank=False, unique=True)
description = models.CharField(max_length=500, blank=False)
class AssocMember(models.Model):
class Meta:
unique_together = (("user", "assoc"),)
user = models.ForeignKey('user.User')
assoc = models.ForeignKey('associations.Association')
is_admin = models.BooleanField(default=False)
group = models.SmallIntegerField(default=-1)
class Event(models.Model):
name = models.CharField(max_length=40, blank=False)
date = models.DateTimeField(blank=False)
assoc = models.ForeignKey('associations.Association')
group = models.IntegerField(blank=True, default=-1)
I would need to implement a get_queryset()
in my API that returns all the events of the connected user corresponding to its group. But for that, I have to access AssocMember for each event during the filtering, and create a custom condition (like normal .filter()
in Python)
What is the best way to do so with Django REST filters ?
Thanks in advance.
Check out a ModelViewSet. You can override the
get_queryset
method to filter based onrequest.user
: