[Fixed]-Use Django GenericForeignKey to store basic notifications


I’m actually new to this but I used a little bit of this before, so I just share my experience with GenericForeignKey.

Basically you want to define the content type and the id fields in the model, then a third field to combine them so that you could easily look it up later on, like this:

class UserActivity(models.Model):
    activity_ct = models.ForeignKey(ContentType)
    activity_id = models.PositiveIntegerField()
    activity = generic.GenericForeignKey('activity_ct', 'activity_id')

When you save/query, you do this:

from django.contrib.contenttypes.models import ContentType

activity_obj = UserFollowers.objects.get(id=1)
activity_ct = ContentType.objects.get_for_model(activity_obj)
activity_create = UserActivity.objects.create(activity_ct=activity_ct, 
activity_query = UserActivity.objects.filter(activity_ct=activity_ct,

The good part is that when you want to pull the UserActivity’s activity object, you can just do activity_obj.activity. I’m not sure if it’s exactly your plan but the mechanism is the same. Hope this helps.

Leave a comment