dabljues
dabljues

Reputation: 1947

DRF get_queryset check if in ManyToManyField

I have a model like this:

class Project(models.Model):
    name = models.CharField("Name", max_length=8, unique=True)
    status = models.CharField(
        "Status",
        max_length=1,
        choices=[("O", "Open"), ("C", "Closed")],
        default="O",
    )
    description = models.CharField("Description", max_length=3000, default="")

    owner = models.ForeignKey(
        User, on_delete=models.SET_NULL, null=True, related_name="project_owner"
    )
    participants = models.ManyToManyField(User, related_name="project_participants", blank=True)

    created_at = models.DateTimeField(auto_now_add=True)

Now in this model's ViewSet I have a get_queryset method:

def get_queryset(self):
    if self.request.user.is_superuser:
        return Project.objects.all()
    else:
        return Project.objects.filter(owner=self.request.user.id)

So when I get a project or projects, I only search for the projects that a user (hidden in the request, in JWT) owns. But now I thought about searching for the projects that user participates in (so the user appears in participants field list).

How can I do that in get_queryset?

Upvotes: 1

Views: 70

Answers (1)

Brian Destura
Brian Destura

Reputation: 12068

It should be possible with using Q:

Project.objects.filter(
    Q(owner=self.request.user.id) | 
    Q(participants=self.request.user.id)
)

https://docs.djangoproject.com/en/3.2/topics/db/queries/#complex-lookups-with-q-objects

Upvotes: 1

Related Questions