userData.py 1.63 KB
Newer Older
1
from django.db import models
2
from rest_framework import serializers
Florent Chehab's avatar
Florent Chehab committed
3
from backend.models.university import University
4 5
from backend.fields import JSONField
from backend.models.abstract.my_model import MyModel, MyModelSerializer, MyModelViewSet
Florent Chehab's avatar
Florent Chehab committed
6
from django.contrib.auth.models import User
7
from backend.utils import get_viewset_permissions, get_model_config, get_user_level
8 9


Florent Chehab's avatar
Florent Chehab committed
10
class UserData(MyModel):
Florent Chehab's avatar
Florent Chehab committed
11
    model_config = get_model_config("UserData")
12

13 14
    owner = models.OneToOneField(
        User, on_delete=models.CASCADE, primary_key=True)
Florent Chehab's avatar
Florent Chehab committed
15
    contact_info = JSONField(default=dict)
16
    contact_info_is_public = models.BooleanField(default=False)
Florent Chehab's avatar
Florent Chehab committed
17
    config = JSONField(default=dict)
Florent Chehab's avatar
Florent Chehab committed
18 19
    black_list = models.ManyToManyField(
        University, related_name='+', blank=True)
Florent Chehab's avatar
Florent Chehab committed
20
    other_data = JSONField(default=dict)
21 22


Florent Chehab's avatar
Florent Chehab committed
23 24
class UserDataSerializer(MyModelSerializer):
    owner = serializers.CharField(read_only=True)
25 26 27 28
    owner_level = serializers.SerializerMethodField()

    def get_owner_level(self, obj):
        return get_user_level(obj.owner)
Florent Chehab's avatar
Florent Chehab committed
29 30

    def my_pre_save(self):
31
        self.override_validated_data({'owner': self.user})
Florent Chehab's avatar
Florent Chehab committed
32

33
        # we try to recover the correct instance
34
        query = UserData.objects.filter(owner=self.user)
35 36 37
        if len(query) == 1:
            self.instance = query[0]

38 39 40 41 42
    class Meta:
        model = UserData
        fields = '__all__'


Florent Chehab's avatar
Florent Chehab committed
43
class UserDataViewSet(MyModelViewSet):
44
    permission_classes = get_viewset_permissions("UserDataViewSet")
45
    serializer_class = UserDataSerializer
46
    LIST_SHOULD_BE_DETAIL = True
47

Florent Chehab's avatar
Florent Chehab committed
48 49
    def get_queryset(self):
        return UserData.objects.filter(owner=self.request.user)  # pylint: disable=E1101