1 from django
.db
import models
2 from django
.conf
import settings
3 from django
.contrib
.contenttypes
.models
import ContentType
4 from django
.contrib
.contenttypes
.fields
import GenericRelation
, GenericForeignKey
6 from mygpo
.core
.models
import UpdateInfoModel
9 class Vote(UpdateInfoModel
):
10 """A vote by a user for some object"""
13 user
= models
.ForeignKey(settings
.AUTH_USER_MODEL
, on_delete
=models
.CASCADE
)
15 # the object that was voted for
16 content_type
= models
.ForeignKey(ContentType
, on_delete
=models
.PROTECT
)
17 # this should suit UUID and integer primary keys
18 object_id
= models
.UUIDField()
19 content_object
= GenericForeignKey("content_type", "object_id")
23 # a user can only vote once per object
24 ("user", "content_type", "object_id")
28 class VoteMixin(models
.Model
):
30 votes
= GenericRelation(Vote
, related_query_name
="votes")
36 """Register a vote from the user for the current object"""
37 Vote
.objects
.get_or_create(
39 content_type
=ContentType
.objects
.get_for_model(self
),
44 return self
.votes
.count()