I wanted to implement notifications for my app, so that a user would know if another user, liked, commented on, or followed another user. It works, but I feel like it's very limited which I need to improve.

The model looks like this:

class Notification(models.Model):
    receiver = models.ForeignKey(User, related_name='notifications')
    sender = models.ForeignKey(User, related_name='sent_notifications', blank=True, null=True)

    object_type = models.ForeignKey(ContentType, blank=True, null=True)
    object_id = models.PositiveIntegerField(blank=True, null=True)
    object = GenericForeignKey('object_type', 'object_id')

    type = models.CharField(max_length=3, choices=config.NOTIFICATION_TYPE_OPTIONS)
    unread = models.BooleanField(default=True)

    slug = models.SlugField(max_length=255, unique=False, default='notification')

    # Other
    date_created = models.DateTimeField(auto_now=False, auto_now_add=True, blank=True)
    date_modified = models.DateTimeField(auto_now=True, auto_now_add=False, blank=True)

Here it is explained:

  1. Receiver is the person receiving the notification
  2. The sender, the oposite of receiver.
  3. Object fields, is the generic relation. It might relate to a comment object, a like object, or a follow object, these objects then nest to the content in question.
  4. What type of notification it is. Can be 'Comment', 'Like', 'Follow'
  5. Slug is used to determine if the notification has been posted before, as to avoid spamming the user if another user decides to spam something that would create notifications.

My issue with this is:

  1. How do I handle notifications once they're pointing to an object that has been deleted? (A user deletes the post a comment was on, or the comment itself)
  2. How do I avoid unecessary database queries when retrieving notificiations with nested content?
  3. Finally, displaying a notification is finicky, as there has to be lots of conditions on what type of notification, what type of object it's pointing to, what type of content the object is on (Did the user like a post or a comment?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.