from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models from django.utils.translation import gettext_lazy as _ class Rating(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') ip = models.GenericIPAddressField(verbose_name=_('ip')) class Meta: unique_together = ('ip', 'object_id', 'content_type') @property def name(self): # Check if Generic obj has name or title if hasattr(self.content_object, 'name'): return self.content_object.name if hasattr(self.content_object, 'title'): return self.content_object.title_translated class ViewCount(models.Model): count = models.PositiveIntegerField()