NDOJ/judge/models/bookmark.py

75 lines
2.4 KiB
Python
Raw Normal View History

2022-11-17 19:17:45 +00:00
from django.db import models
from django.db.models import CASCADE
from django.utils.translation import gettext_lazy as _
2022-11-17 21:21:32 +00:00
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
2022-11-17 19:17:45 +00:00
from judge.models.profile import Profile
2024-04-13 22:02:54 +00:00
from judge.caching import cache_wrapper
2022-11-17 19:17:45 +00:00
__all__ = ["BookMark"]
class BookMark(models.Model):
page = models.CharField(
max_length=30,
verbose_name=_("associated page"),
db_index=True,
) # deprecated
score = models.IntegerField(verbose_name=_("votes"), default=0)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
linked_object = GenericForeignKey("content_type", "object_id")
2022-11-17 19:17:45 +00:00
2024-04-13 22:02:54 +00:00
@cache_wrapper(prefix="BMgb")
2024-05-08 15:15:55 +00:00
def is_bookmarked_by(self, user):
2024-04-13 22:02:54 +00:00
return MakeBookMark.objects.filter(bookmark=self, user=user).exists()
2022-11-17 19:17:45 +00:00
class Meta:
verbose_name = _("bookmark")
verbose_name_plural = _("bookmarks")
indexes = [
models.Index(fields=["content_type", "object_id"]),
]
unique_together = ("content_type", "object_id")
2022-11-17 19:17:45 +00:00
def __str__(self):
return f"bookmark for {self.linked_object}"
2022-11-17 19:17:45 +00:00
2022-11-17 22:11:47 +00:00
2022-11-17 19:17:45 +00:00
class MakeBookMark(models.Model):
bookmark = models.ForeignKey(BookMark, related_name="bookmark", on_delete=CASCADE)
2022-11-17 22:11:47 +00:00
user = models.ForeignKey(
Profile, related_name="user_bookmark", on_delete=CASCADE, db_index=True
)
2022-11-17 19:17:45 +00:00
class Meta:
indexes = [
models.Index(fields=["user", "bookmark"]),
]
2022-11-17 19:17:45 +00:00
unique_together = ["user", "bookmark"]
verbose_name = _("make bookmark")
verbose_name_plural = _("make bookmarks")
2024-05-08 15:15:55 +00:00
@cache_wrapper(prefix="gocb", expected_type=BookMark)
2024-04-13 22:02:54 +00:00
def _get_or_create_bookmark(content_type, object_id):
bookmark, created = BookMark.objects.get_or_create(
content_type=content_type,
object_id=object_id,
)
return bookmark
class Bookmarkable:
def get_or_create_bookmark(self):
2024-04-13 22:02:54 +00:00
content_type = ContentType.objects.get_for_model(self)
object_id = self.pk
return _get_or_create_bookmark(content_type, object_id)
def dirty_bookmark(bookmark, profile):
2024-05-08 15:15:55 +00:00
bookmark.is_bookmarked_by.dirty(bookmark, profile)
2024-04-13 22:02:54 +00:00
_get_or_create_bookmark.dirty(bookmark.content_type, bookmark.object_id)