diff --git a/apps/rating/migrations/0002_auto_20191004_0928.py b/apps/rating/migrations/0002_auto_20191004_0928.py new file mode 100644 index 00000000..a172c6f1 --- /dev/null +++ b/apps/rating/migrations/0002_auto_20191004_0928.py @@ -0,0 +1,22 @@ +# Generated by Django 2.2.4 on 2019-10-04 09:28 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('contenttypes', '0002_remove_content_type_name'), + ('rating', '0001_initial'), + ] + + operations = [ + migrations.AlterModelOptions( + name='rating', + options={}, + ), + migrations.AlterUniqueTogether( + name='rating', + unique_together={('ip', 'object_id', 'content_type')}, + ), + ] diff --git a/apps/rating/models.py b/apps/rating/models.py index 61e4378d..e1dcec86 100644 --- a/apps/rating/models.py +++ b/apps/rating/models.py @@ -10,6 +10,9 @@ class Rating(models.Model): 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 diff --git a/apps/rating/tasks.py b/apps/rating/tasks.py index 0e176910..5c2653a0 100644 --- a/apps/rating/tasks.py +++ b/apps/rating/tasks.py @@ -1,5 +1,4 @@ -from datetime import timedelta -from celery import task +from celery import shared_task from rating.models import Rating from django.contrib.contenttypes.models import ContentType @@ -10,13 +9,10 @@ def add_rating(remote_addr, pk, model, app_label): ) -@task +@shared_task def add(remote_addr, pk, model, app_label): - rating = Rating() - rating.ip = remote_addr - rating.object_id = pk - rating.content_type = ContentType.objects.get(app_label=app_label, model=model) - rating.save() - + content_type = ContentType.objects.get(app_label=app_label, model=model) + Rating.objects.get_or_create( + ip=remote_addr, object_id=pk, content_type=content_type)