ManyToMany 消息的 Django 对话类别

Django conversation categories for messages with ManyToMany

我正在用 Django 制作一种社交网络。这基本上解释了我在做什么:

谈话完全是两个人之间的,而不是更多。我有一个对话模型,因为当他们收到他们的消息时,我希望用户有一个与他们有消息的其他用户的列表。

相关观点如下:

def writemessage(request, id):
    profile = Profile.objects.get(id=id)
    context = {
        'profile': profile,
    }
    if request.method == 'POST':
        sender = request.user
        receiver = profile.user
        content = request.POST['content']
        timestamp = datetime.now()
        print(sender, receiver, content, timestamp)
        record = Message(sender=sender, receiver=receiver, content=content, timestamp=timestamp)
        record.save()
        senderprofile = Profile.objects.get(user=sender)
        receiverprofile = Profile.objects.get(user=receiver)
        record.conversation.add(senderprofile)
        record.conversation.add(receiverprofile)
        print(senderprofile, receiverprofile)
        return redirect('messagespage')
    return render(request, 'thecode/writemessage.html', context)

这是我的模型:

from django.db import models
from django.contrib.auth.models import User

# Create your models here.

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    city = models.CharField(max_length=60)
    country = models.CharField(max_length=60)
    skillstolearn = models.CharField(max_length=200)
    skillstoteach = models.CharField(max_length=200)
    description = models.TextField()

    def __str__(self):
        return self.user.username

class Conversation(models.Model):
    participants = models.ManyToManyField(User)
    
    def __str__(self):
        return self.participants

class Message(models.Model):
    sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender')
    receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver')
    content = models.TextField()
    conversation = models.ForeignKey(Conversation, default=None, on_delete=models.CASCADE, null=True)
    timestamp = models.DateTimeField()

    def __str__(self):
        return self.sender.username + ' to ' + self.receiver.username

我知道一些文档:

https://docs.djangoproject.com/en/dev/ref/models/relations/

我试图理解文档并在此处发帖,但有点卡住了。

'NoneType' 对象没有属性 'add' = 我收到的错误消息

Message 对象的 conversation 字段默认为 None,并且您的视图函数在尝试读取它之前不会设置 conversation。你需要弄清楚这个消息属于什么 Conversation ,然后在构造 Message:

时设置它
record = Message(conversation=???, sender=sender, receiver=receiver, content=content, timestamp=timestamp)
        record.save()

你怎么知道 User 在哪个对话中?

一些代码审查笔记:

  • ForeignKey 字段的 related_name 参数表示 User 模型上的字段名称,该模型将 back 引用到 Message模型,而不是反过来。因此,它们应该是 messages_sentmessages_received,而不是 senderreceiver。请更新您的原始帖子以提高清晰度。
    # Example of accessing sent and received messages from a User model:
    user.messages_sent
    user.messages_received