Contents
django-cms-api is a Django CMS 4.1 project with PostgreSQL, a Django REST Framework API and a React frontend, started with Docker Compose. Most of it is scaffolding. The part worth reading is the social_features app, which gives likes, dislikes and comments to any model without a new table for each one.
This post walks through how that works: a generic foreign key, a unique constraint and a toggle endpoint. It also covers where the code stops short of the README's claim that the system "works with any model", because that gap is as instructive as the design.
Pointing at any row with a generic foreign key
A normal foreign key points at one table. A Like has to point at a CMS page, a comment or whatever model comes next, so it uses Django's contenttypes framework (django.contrib.contenttypes is enabled in settings.py).
class Like(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='likes')
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
unique_together = ('user', 'content_type', 'object_id')
indexes = [
models.Index(fields=['content_type', 'object_id']),
]content_type says which model, object_id says which row, and GenericForeignKey joins them so like.content_object returns the real instance. The index on those two columns serves the query every request makes: all likes for one object.
Three limits follow from this shape. The database cannot enforce a foreign key to the target, so a like for a row that does not exist is accepted. object_id is a PositiveIntegerField, so only models with integer primary keys fit. And no target model declares a GenericRelation, so deleting a page leaves its likes behind. "Any model" really means any model with an integer key.
One reaction per user per object
The unique_together line is what limits a user to one like per object, and it is applied in the initial migration. Dislike is a separate model with the same fields and the same constraint.
That split decides where each rule lives:
| Rule | Where it is enforced |
|---|---|
| One like per user per object | Database, unique constraint on Like |
| One dislike per user per object | Database, unique constraint on Dislike |
| Never a like and a dislike together | View code only |
| The target object exists | Nowhere |
| The content type exists | The toggle view, by catching DoesNotExist |
A toggle endpoint
The client does not decide between "add" and "remove". It sends the same POST /api/social/likes/toggle/ with a content_type and an object_id, and the server works out the rest.
@action(detail=False, methods=['post'])
def toggle(self, request):
content_type = request.data.get('content_type')
object_id = request.data.get('object_id')
# ... missing-parameter check trimmed ...
try:
ct = ContentType.objects.get(model=content_type)
except ContentType.DoesNotExist:
return Response({'error': 'Invalid content_type'},
status=status.HTTP_400_BAD_REQUEST)
like, created = Like.objects.get_or_create(
user=request.user, content_type=ct, object_id=object_id)
if not created:
like.delete()
return Response({'status': 'unliked'}, status=status.HTTP_200_OK)
# Remove dislike if exists
Dislike.objects.filter(
user=request.user, content_type=ct, object_id=object_id).delete()
return Response(LikeSerializer(like).data, status=status.HTTP_201_CREATED)get_or_create returns a created flag. If it is false, the user had already liked the object, so the row is deleted. If it is true, the opposite reaction is removed. DislikeViewSet mirrors this with the roles swapped, and the plain create route calls the same opposite-delete in perform_create.
Counts
Comments are the one place the repo exposes like counts. Comment has two properties, and the serializer lists them as read-only fields.
@property
def likes_count(self):
return Like.objects.filter(
content_type=ContentType.objects.get_for_model(Comment),
object_id=self.id
).count()This also shows the genericness at work: the frontend renders LikeDislikeButton with contentType="comment" for each comment, so comment reactions share the table with everything else. The cost is a COUNT query per comment per direction, and replies are serialized recursively, so a long thread costs a lot of queries. I did not add annotations or caching.
For other models there is no count field. The list endpoint filters on content_type__model and object_id, and the global DRF settings use page-number pagination with a page size of 20, so the count has to come from the paginated response. The frontend defines getLikes but never calls it. The demo page passes hard-coded numbers, and the button starts with userLiked set to false, so after a reload it does not show your earlier reaction.
What I would change
The design is fine for a small project where every liked model has an integer key. The shape I like least is two tables. A single reaction model with a value of 1 or -1 would put "one reaction per object" under one unique constraint, so the database would enforce it and toggle would not need the opposite-delete step.
I would also wrap toggle in transaction.atomic, look up the content type by app label and model, and annotate counts instead of counting per row. The viewsets are ModelViewSets with IsAuthenticatedOrReadOnly and no ownership check, so the plain update and delete routes should be restricted before this goes public. The repo has no tests, so I would write them first.
Found this useful? Share it with your team.