userData.py 1.46 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
Florent Chehab's avatar
Florent Chehab committed
4
from backend.models.tools import JSONField
Florent Chehab's avatar
Florent Chehab committed
5
6
from backend.models.my_model import MyModel, MyModelSerializer, MyModelViewSet
from django.contrib.auth.models import User
Florent Chehab's avatar
Florent Chehab committed
7
from backend.utils import get_viewset_permissions, get_model_config
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

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


Florent Chehab's avatar
Florent Chehab committed
22
23
24
25
class UserDataSerializer(MyModelSerializer):
    owner = serializers.CharField(read_only=True)

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

28
        # we try to recover the correct instance
29
        query = UserData.objects.filter(owner=self.user)
30
31
32
        if len(query) == 1:
            self.instance = query[0]

33
34
35
36
37
    class Meta:
        model = UserData
        fields = '__all__'


Florent Chehab's avatar
Florent Chehab committed
38
class UserDataViewSet(MyModelViewSet):
39
    permission_classes = get_viewset_permissions("UserDataViewSet")
40
    serializer_class = UserDataSerializer
41
42
    BYPASS_DICT_MODE = True
    
Florent Chehab's avatar
Florent Chehab committed
43
44
    def get_queryset(self):
        return UserData.objects.filter(owner=self.request.user)  # pylint: disable=E1101