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
26
27
28
class UserDataSerializer(MyModelSerializer):
    owner = serializers.CharField(read_only=True)

    def my_pre_save(self):
        user = self.get_user_in_request()
        self.override_validated_data({'owner': user})

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

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


Florent Chehab's avatar
Florent Chehab committed
39
class UserDataViewSet(MyModelViewSet):
40
    permission_classes = get_viewset_permissions("UserDataViewSet")
41
    serializer_class = UserDataSerializer
Florent Chehab's avatar
Florent Chehab committed
42
43
44

    def get_queryset(self):
        return UserData.objects.filter(owner=self.request.user)  # pylint: disable=E1101