I'm trying to filter activities in a task (list of activities) by the assigned user group.
TaskActivityModel.objects.filter(activity__workCenter=request.user.groups)
this gives me a TypeError: Field 'id' expected a number
when I amend the filter parameter to request.user.groups.id
I get an AttributeError: 'ManyRelatedManager' object has no attribute 'id'
. What am I missing?
Each activity has a single group assigned to it. The users can be a in many groups. Could this be the issue
TaskActivityModel
class TaskActivityModel(models.Model):
task = models.ForeignKey(TaskModel, on_delete=models.PROTECT)
activity = models.ForeignKey(ActivityModel, on_delete=models.PROTECT)
startTime = models.DateTimeField(default=timezone.now)
finishTime = models.DateTimeField(null=True)
ActivityModel
class ActivityModel(models.Model):
activityName = models.CharField(max_length=100)
description = models.CharField(max_length=200)
workCenter = models.ForeignKey(Group, on_delete=models.PROTECT)
history = HistoricalRecords()
So it's exactly as you say. User can be in multiple groups because of that request.user.groups returns a ManyRelatedManager. To get all ids of user groups you have to query that manager to get all objects. You can do this in following way: request.user.groups.all()
.
Also as the returned value will be an array you will have to use __in
in your ORM query so it checks if workCenter is in user's groups. Like this:
TaskActivityModel.objects.filter(activity__workCenter__in=request.user.groups.all())
You can read more about Many To Many relations in Django here: https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_many/