0

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 Answer 1

0

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)
Sign up to request clarification or add additional context in comments.

1 Comment

The problem is that the variable "group" depends on each event, because an event is related to an association, and the group of a user depends on this association). I found kind of a solution by turning the queryset into a list and using python filter function, but it seems ugly (I can't convert the list back to a queryset after)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.