KitKit
KitKit

Reputation: 9563

Django: ContentType object access, Get user from the content_object

Helllo everyone, I have no solution to Get User who owns the Content Object in Django. So I post for your guys help!

I'm building 2 models: Reaction and Notification. If user React, Notification will auto be created a object. This is my code: Model Reaction:

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)

Models Notification

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')

As you saw, I have problem with get to_user fields. This field I want to get User who owner a Content Object in Django Example: Post, Comment, ... Please help me with this case!

Upvotes: 0

Views: 239

Answers (1)

rajkris
rajkris

Reputation: 1793

Maybe try this, assuming that the content_object has a user relation:

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()

Upvotes: 1

Related Questions