Good day! I describe api correspondence between users.

I create a new message, write down the message text, specify the current authorized user as the sender. I also accept the user to find the necessary correspondence or create a new one. But Model Message does not contain the recipient field, so I’m catching the error. How do I get around this?

class CreateSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) content = serializers.CharField() recipient = serializers.PrimaryKeyRelatedField(queryset=User.objects.all()) thread = None def create(self, validated_data): user = self.context['request'].user message = Message.objects.create( thread=self.thread, sender=user, content=validated_data['content'] ) self.thread.userthread_set.exclude(user=user).update(deleted=False, unread=True) self.thread.userthread_set.filter(user=user).update(deleted=False, unread=False) return message def validate_recipient(self, recipient): sender = self.context['request'].user if sender == recipient: raise serializers.ValidationError('Вы не можете писать самому себе.') thread = Thread.objects.filter(Q(userthread__user=sender) and Q(userthread__user=recipient)).first() # создаем переписку если ее нету if not thread: thread = Thread.objects.create() self.thread.userthread_set.create(user=recipient, deleted=False, unread=True) self.thread.userthread_set.create(user=sender, deleted=True, unread=False) self.thread = thread return recipient 

AttributeError at / api / v1 / messages / create / 'Message' object has no attribute 'recipient'

Here are the models describing the correspondence, as such, the sender - the recipient does not exist, there is the sender of the message, and subscribers to the correspondence

 class Thread(models.Model): subject = models.CharField(max_length=150) users = models.ManyToManyField(settings.AUTH_USER_MODEL, through="UserThread") def __str__(self): return "{}: {}".format( self.subject, ", ".join([str(user) for user in self.users.all()]) ) class UserThread(models.Model): thread = models.ForeignKey(Thread) user = models.ForeignKey(settings.AUTH_USER_MODEL) unread = models.BooleanField() deleted = models.BooleanField() class Message(models.Model): thread = models.ForeignKey(Thread, related_name="messages") sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="sent_messages") sent_at = models.DateTimeField(default=timezone.now) content = models.TextField() class Meta: ordering = ("sent_at",) 
  • one
    Well, if this is a correspondence between users, how can it be without a recipient? Show the model. - Sergey Panasenko

0