我正在做基本的消息应用,用户可以发送消息给其他用户...
这里是我的models.py
class Messages(Model):
created_at = DateTimeField(null=True, blank=True, auto_now_add=True, editable=False,
verbose_name='Yaratılma Tarihi')
message = TextField(max_length=500, verbose_name='Mesaj', null=True, blank=True, )
sender = ForeignKey('dentis.User', verbose_name='Gönderen', related_name='User')
target = ForeignKey('dentis.User', verbose_name='Alıcı', related_name='target')
read_at = BooleanField(default=False, verbose_name='Okundu', blank=True, )
class Meta:
verbose_name = 'Mesaj'
verbose_name_plural = 'Mesajlar'
def __str__(self):
return u'%s / %s/' % (self.sender.email, self.message[:15])
def get_type(self):
return 'message'
这里我的其他api观点
class MessageAPIView(ModelViewSet):
serializer_class = MessageSerializer
filter_backends = (filters.DjangoFilterBackend,)
filter_class = MessageUserFilter
permission_classes = (AuthenticatedUserOnly,)
def get_user(self):
if self.request.user.is_authenticated():
return self.request.user
else:
raise Http404
def get_queryset(self):
messages = Messages.objects.filter(
Q(sender=self.get_user()) | Q(target=self.get_user())).order_by('-created_at').distinct()
return messages
def perform_create(self, serializer):
if self.request.user.is_authenticated():
try:
target_email = serializer.validated_data['target']['email']
target = User.objects.get(email=target_email)
except User.DoesNotExist:
raise ValidationError('Hedef Kullanıcı bulunamadı')
except KeyError:
raise ValidationError('Hedef kullanıcı belirtilmedi')
sender = self.request.user
serializer.save(sender=sender, target=target)
else:
raise Http404
我的序列化工具
class MessageSerializer(ModelSerializer):
sender = UserMobileSerializer(read_only=True)
target = UserMobileSerializer()
class Meta:
model = Messages
fields = '__all__'
当我发送消息时,请返回此错误:
第163行,在perform_create中 target_email = serializer.validated_data ['target'] ['email']
TypeError:'用户'对象不可订阅
[28 / Apr / 2018 18:56:04]“POST / api / v1 / message / HTTP / 1.1”500 15742
我的用户模型使用
USERNAME_FIELD ='email'
不使用用户名字段
答案 0 :(得分:1)
validated_data['target']
为您提供目标字段的值 - 正如错误所示,它是User的一个实例。您可以使用普通属性语法来访问其字段。
target_email = serializer.validated_data['target'].email