Chuck Aguilar
Chuck Aguilar

Reputation: 2048

Filter queryset with one of two criteria that match with the user. Django Rest Framework

I have this model:

class MessageViewSet(viewsets.ModelViewSet):
    queryset = Message.objects.all()
    serializer_class = MessageSerializer

and of course, it returns every message.

A Message is so in the model:

class Message(models.Model):
    created = models.DateTimeField(auto_now_add=True)

    type = models.CharField(_('type'), choices=MESSAGE_TYPE, default='Invitation', max_length=100)
    content = models.TextField(_('content'), blank=False)
    sender = models.ForeignKey(User, related_name='sender_message', verbose_name=_("Sender"), )
    recipient = models.ForeignKey(User, related_name='receiver_message', null=True, blank=True,
                                  verbose_name=_("Recipient"))
    url_profile_image = models.URLField(_('url_profile_image'), max_length=500, blank=True, default='')

    class Meta:
        ordering = ('created',)

and the serializer is so:

class MessageSerializer(serializers.ModelSerializer):
    sender = serializers.ReadOnlyField(source='sender.uuid')
    recipient = serializers.ReadOnlyField(source='recipient.uuid')

    class Meta:
        model = Message
        fields = ('url', 'id', 'type', 'content', 'sender', 'recipient', 'url_profile_image')

I just want that the queryset returns a message if the user is the sender or the recipient.

I was trying with this:

filter_backends = filters.DjangoFilterBackend
filter_fields = ('recipient', 'sender')

But it doesn't work, perhaps, because I don't know where to compare.

Upvotes: 0

Views: 269

Answers (1)

Sayse
Sayse

Reputation: 43300

You need to define a get_queryset method on the viewset rather than the queryset field.

You can then access the request object to access the current user.

def get_queryset(self):
    return Message.objects.filter(Q(recipient=self.request.user) | Q(sender=self.request.user))

You can find another example in the docs for ModelViewSet

Upvotes: 1

Related Questions