Python Django:ContentType对象访问,从content\u对象获取用户

Python Django:ContentType对象访问,从content\u对象获取用户,python,django,django-models,Python,Django,Django Models,大家好,我没有办法找到Django中内容对象的所有者。所以我想请你们帮忙 我正在构建两个模型:反应和通知。如果用户做出反应,通知将自动创建一个对象。这是我的代码: 模型反应: class Reaction(models.Model): user = models.ForeignKey(User) react_type = models.CharField(max_length=100, choices=REACT_TYPES, default='NO') timestam

大家好,我没有办法找到Django中内容对象的所有者。所以我想请你们帮忙

我正在构建两个模型:反应和通知。如果用户做出反应,通知将自动创建一个对象。这是我的代码: 模型反应:

class Reaction(models.Model):
    user = models.ForeignKey(User)
    react_type = models.CharField(max_length=100, choices=REACT_TYPES, default='NO')
    timestamp = models.DateTimeField(auto_now_add=True, null=True)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True)
    object_id = models.PositiveIntegerField(null=True)
    content_object = GenericForeignKey('content_type', 'object_id')

    def save(self, force_insert=False, force_update=False, *args, **kwargs):
       Notification(from_user = self.user, to_user = ???, notification_type = Notification.LIKED, target_content_type = self.content_type, target_object_id = self.object_id).save()
       super(Reaction, self).save(*args, **kwargs)
模型通知

class Notification(models.Model):    
    from_user = models.ForeignKey(User, related_name='from_user_noti')
    to_user = models.ForeignKey(User, related_name='to_user_noti')
    date = models.DateTimeField(auto_now_add=True, null=True)
    is_read = models.BooleanField(default=False)
    target_content_type = models.ForeignKey(ContentType, related_name='notify_target', blank=True, null=True)
    target_object_id = models.PositiveIntegerField(null=True)
    target = GenericForeignKey('target_content_type', 'target_object_id')
正如您所看到的,我对get to_用户字段有问题。我想获取Django示例中拥有内容对象的用户的字段:Post、Comment、。。。
请帮我拿这个箱子

假设content\u对象具有用户关系,可以尝试以下操作:

class Reaction(models.Model):
    user = models.ForeignKey(User)
    react_type = models.CharField(max_length=100, choices=REACT_TYPES, default='NO')
    timestamp = models.DateTimeField(auto_now_add=True, null=True)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True)
    object_id = models.PositiveIntegerField(null=True)
    content_object = GenericForeignKey('content_type', 'object_id')

    def save(self, force_insert=False, force_update=False, *args, **kwargs):
       super(Reaction, self).save(*args, **kwargs)
       Notification(from_user = self.user, to_user = self.content_object.user, notification_type = Notification.LIKED, target_content_type = self.content_type, target_object_id = self.object_id).save()

在通知中,对于from_user和to_user,您应该有不同的相关_名称,并且这些相关_名称应该是字母数字,而不是“+”。很抱歉,我在复制粘贴中犯了错误。我改了!!嗯,在反应模型中可以有另一个to_user字段。@SandeepBalagopal我认为这个解决方案是在数据库中增加更多的槽。有解决方案吗?反应模型有一个foreignkey到通知模型呢?你可能需要考虑重构模型。我得到这个错误:RajkRISE属性错误:“NoType”对象没有属性“用户”是针对反应对象保存的内容对象,抱歉。超级实际上不返回任何东西。更新了代码。请查收。