Save the user from one model to the another model

风流意气都作罢 提交于 2019-12-06 11:37:06

If you don't want to actively pull the user set as dm03514 showed, such as if you want to add users to the thread by default but maintain the ability to remove them from the thread many-to-many later, you can indeed do this by overriding the save method or by using a post_save signal.

save is good enough for almost all cases - the advantage of post_save is that it can more reliably distinguish between saving a new message and saving edits to an existing message. But if you're not creating messages with preselected PKs or loading them from fixtures save can work fine:

class Message(models.Model):
    def save(self, *args, **kwargs):
        probably_new = (self.pk is None)
        super(Message, self).save(*args, **kwargs)
        if probably_new:
            self.thread.user.add(self.sender)

A signal would look like this:

from django.db.models.signals import post_save

def update_thread_users(sender, **kwargs):
    created = kwargs['created']
    raw = kwargs['raw']
    if created and not raw:
        instance = kwargs['instance']
        instance.thread.user.add(instance.sender)

post_save.connect(update_thread_users, sender=Message)

And then review the docs on preventing duplicate signals in case of multiple imports: https://docs.djangoproject.com/en/dev/topics/signals/#preventing-duplicate-signals

You could lookup the reverse foreign key and get all the users for a particular thread without having to manually put it in Thread

Then you can get users associated with a thread by the reverse lookup:

User.objects.filter(message__thread=thread)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!