-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
74 lines (60 loc) · 2.5 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
from django.contrib.auth.models import User
from django.db import models
from hierarchy.models import Department
class StudentStatus(models.Model):
title = models.CharField(max_length=256, null=False)
status_level = models.PositiveSmallIntegerField(default=0, null=False)
can_publish_without_moderation = models.BooleanField(default=False, null=False)
can_moderate = models.BooleanField(default=False, null=False)
def __str__(self):
return self.title
def as_dict(self):
return {
'id': self.id,
'title': self.title,
'level': self.status_level,
'can_publish_without_moderation': self.can_publish_without_moderation,
'can_moderate': self.can_moderate,
}
class StudentInfo(models.Model):
avatar = models.ImageField(
upload_to='resources/user_avatars/',
default='resources/default/user_ava.png',
null=True, blank=True
)
user = models.OneToOneField(User, on_delete=models.CASCADE)
status = models.ForeignKey(StudentStatus, on_delete=models.CASCADE)
department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True, default=None)
karma = models.SmallIntegerField(default=10, null=False)
course = models.PositiveSmallIntegerField(null=True, blank=True)
def __str__(self):
return self.user.username
def calculate_karma(self):
from posts.models import Post, Comment
karma = 0
if self.department is not None:
karma += 50
if self.course is not None:
karma += 30
if self.avatar != StudentInfo._meta.get_field('avatar').get_default():
karma += 50
karma += 15 * Post.objects.filter(author=self.user).count()
karma += 5 * Comment.objects.filter(author=self.user).count()
return karma
def as_dict(self):
return {
'id': self.id,
'user': {
'username': self.user.username,
'first_name': self.user.first_name,
'last_name': self.user.last_name,
'email': self.user.email,
'last_login': self.user.last_login,
'date_joined': self.user.date_joined,
},
'avatar': self.avatar.url,
'status': self.status.as_dict(),
'karma': self.calculate_karma(),
'course': self.course,
'department': self.department.as_dict() if self.department is not None else None,
}