简体   繁体   中英

Django filter foreign key relationships by user group

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM