Home > Net >  Check if User sending request is in different model
Check if User sending request is in different model

Time:02-10

I'm trying to create an API using the REST Framework. I ran into a little problem. I want to be able to get a list of events for a specific user by sending a request to the API. Is there a possibility to check if the User sending the request is in the team the event belongs to when an event list is requested?

class Teams(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(max_length=1000, blank=True)
    Users = models.ManyToManyField(User, blank=True)

class Event(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    eventTime = models.DateTimeField()
    title = models.CharField(max_length=100, default='')
    description = models.TextField(max_length=1000, blank=True)
    group = models.ForeignKey(Teams, on_delete=models.CASCADE)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

those are the realtionships between the models i implemented so far

CodePudding user response:

You can do that by overwriting .get_queryset(). This should do the trick:

class EventList(generics.ListAPIView):

    def get_queryset(self):
        # 
        return Event.objects.filter(group__users=self.request.user)

Querying many-to-many fields is (in my opinion) not very intuitive.

Event.objects.filter(group__users=self.request.user) basically means "get all events that have a group/team that contain the current user".

  • Related