gpt4 book ai didi

django - 类型错误 : 'User' object is not subscriptable

转载 作者:行者123 更新时间:2023-12-01 23:40:05 25 4
gpt4 key购买 nike

我正在为用户做基本的消息应用程序,可以向其他用户发送消息...

这里是我的 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 View

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__'

当我发送消息时返回此错误:

line 163, in perform_create target_email = serializer.validated_data['target']['email']

TypeError: 'User' object is not subscriptable

[28/Apr/2018 18:56:04] "POST /api/v1/message/ HTTP/1.1" 500 15742

我的用户模型使用

USERNAME_FIELD = 'email'

不使用用户名字段

最佳答案

validated_data['target'] 为您提供目标字段的值 - 正如错误所述,它是 User 的实例。您可以使用普通的属性语法来访问其字段。

target_email = serializer.validated_data['target'].email

关于django - 类型错误 : 'User' object is not subscriptable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50080147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com