Py学习  »  Django

如何使用djago信号从django中的manytomanyfield获取用户,并使用received many to many用户字段创建另一个对象

John • 4 年前 • 844 次点击  

我想知道有没有什么方法可以让我们使用信号在一个模型中获得更新的多对多字段并将它们发布到另一个模型

class Post(models.Model):

    name=models.CharField(max_length=24)
    nc=models.ManyToManyField(settings.AUTH_USER_MODEL)
    def __str__(self):
        return self.name
        # return self.name
m2m_changed.connect(receiver=like_post,sender=Post.nc.through)

我想在post model的nc字段中收集更新的记录,并使用信号创建一个使用函数的对象 这是连接到POST模型的信号

def like_post(sender, *args, **kwargs):
    # if kwargs['action'] in ('post_update'):
    if kwargs['action'] in ('post_add', 'post_remove','post_update'):

        print(kwargs['instance'])
        instance = kwargs['instance']
        print(instance)
        notify = Notify.objects.create(
                 recipient=instance,
                 creator=Post.objects.get(pk=50),
                  state='unread',
                   type=kwargs['action'],
                )
    else:
        print('no instance') 

在收件人和创建者部分,我想用一个现有的用户对象更新这些字段创建者是更新manytomanyfield的人,收件人是创建该帖子的人

notify model:
class Notify(models.Model):
    recipient = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='notify_recipient',on_delete=models.CASCADE)
    creator = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='notify_sender',on_delete=models.CASCADE)
    state = ('read', 'unread', 'unseen')
    type = models.CharField(max_length=30, blank=True)
    url = models.CharField(max_length=50, blank=True)

每当我运行这个实例时,它只打印post对象名并引发这个错误

ValueError at /admin/posts/post/50/change/
Cannot assign "<Post: ok>": "Notify.recipient" must be a "User" instance.
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46009
 
844 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Sanip
Reply   •   1 楼
Sanip    4 年前

你可以看到 通知 类定义 receipent 作为 验证用户模型 ,但您正在创建 通知 你的信号是:

notify = Notify.objects.create(
                 recipient=instance,
                 creator=Post.objects.get(pk=50),
                  state='unread',
                   type=kwargs['action'],
                )

这里, 实例 Post 而不是 User 你在用 post 创建者字段中的实例 . 这就是导致错误的原因。

要解决此错误,需要在这些字段中传递用户实例。例如,您可以使用以下内容:

notify = Notify.objects.create(
                     recipient=instance.nc, # find out how to pass the user of the post here
                     creator=Post.objects.get(pk=50), # replace by an user instance here instead of a post instance 
                      state='unread',
                       type=kwargs['action'],
                    )

编辑: 要确保保存用户实例,需要覆盖 save_model 用于后期模型的modeladmin方法为:

class PostAdmin(admin.ModelAdmin):
    def save_related(self, request, form, formsets, change):
    if not form.cleaned_data['nc']:
        form.cleaned_data['nc'] = [request.user]
    form.save_m2m()