我有这个型号:
class MessageViewSet(viewsets.ModelViewSet):
queryset = Message.objects.all()
serializer_class = MessageSerializer
当然,它会返回每条消息。
模型中有一条消息:
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',)
并且序列化器是这样的:
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')
我只是希望如果用户是发件人或收件人,则查询集会返回一条消息。
我正在尝试这个:
filter_backends = filters.DjangoFilterBackend
filter_fields = ('recipient', 'sender')
但也许不行,因为我不知道在哪里比较。
答案 0 :(得分:1)
您需要在视图集上定义get_queryset
方法,而不是queryset
字段。
然后,您可以访问请求对象以访问当前用户。
def get_queryset(self):
return Message.objects.filter(Q(recipient=self.request.user) | Q(sender=self.request.user))