Migrate pagevote and bookmark to use content_type

This commit is contained in:
cuom1999 2023-08-03 16:04:39 +07:00
parent 64495be799
commit 36e27321f7
19 changed files with 285 additions and 87 deletions

View file

@ -2,6 +2,8 @@ from django.db import models
from django.db.models import CASCADE
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from judge.models.profile import Profile
@ -13,7 +15,11 @@ class BookMark(models.Model):
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")
def get_bookmark(self, user):
userqueryset = MakeBookMark.objects.filter(bookmark=self, user=user)
@ -22,31 +28,16 @@ class BookMark(models.Model):
else:
return False
def page_object(self):
from judge.models.contest import Contest
from judge.models.interface import BlogPost
from judge.models.problem import Problem, Solution
try:
page = self.page
if page.startswith("p:"):
return Problem.objects.get(code=page[2:])
elif page.startswith("c:"):
return Contest.objects.get(key=page[2:])
elif page.startswith("b:"):
return BlogPost.objects.get(id=page[2:])
elif page.startswith("s:"):
return Solution.objects.get(problem__code=page[2:])
return None
except ObjectDoesNotExist:
return None
class Meta:
verbose_name = _("bookmark")
verbose_name_plural = _("bookmarks")
indexes = [
models.Index(fields=["content_type", "object_id"]),
]
unique_together = ("content_type", "object_id")
def __str__(self):
return self.page
return f"bookmark for {self.linked_object}"
class MakeBookMark(models.Model):
@ -56,6 +47,9 @@ class MakeBookMark(models.Model):
)
class Meta:
indexes = [
models.Index(fields=["user", "bookmark"]),
]
unique_together = ["user", "bookmark"]
verbose_name = _("make bookmark")
verbose_name_plural = _("make bookmarks")