Helllo大家,我没有解决方案来获取拥有Django内容对象的用户。所以我发帖给你们帮忙!
我正在构建2个模型:反应和通知。如果用户React,将自动创建一个对象Notification。这是我的代码: 模型反应:
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')
如您所见,我对获取to_user
字段有疑问。这个字段我想得到拥有Django内容对象的用户示例:发布,评论,...
请帮我处理这个案子!
答案 0 :(得分:1)
假设content_object具有用户关系,可以尝试这个:
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()