Django REST Framework : filtering with another tab

2019-09-13 23:59发布

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.

1条回答
Juvenile、少年°
2楼-- · 2019-09-14 00:21

Check out a ModelViewSet. You can override the get_queryset method to filter based on request.user:

class EventViewSet(viewsets.ModelViewSet):
    def get_queryset(self):
        group = self.request.user.group  # Your models might need adjusting to do this
        return Event.objects.filter(group__in=group)
查看更多
登录 后发表回答