Recommand · June 2, 2021 0

Django 3 – null value in column "x" of relation

I’m struggling with the django rest project.

I want to have some data in my database visible only for current logged in user.
I did it by using my serializer and filtering – it’s working.

The next step is to add data to the database.
My purpose is to add data only by admin user, so I have added my custom permission class:
permission_classes = (IsAdminOrReadOnly,).
Admin also has to have the possibility to specify used owned the data.
It’s working when I’m using django admin panel.

And finally I want to post the data e.g:

{
  "unix": 0,
  "user": "example@email.com"
}

Based on the email – I want to specify the user and assign posted data to the user.

I have some idea how to resolve this but right now I’m struggling with the error:

django.db.utils.IntegrityError: null value in column "user_id" of relation "rest_userstats" violates not-null constraint

But did not find the solution yet

I did prepare some model class:
models.py

class UserStats(models.Model):
    user = models.ForeignKey(get_user_model(), related_name='statistics', on_delete=models.CASCADE)
    user_email = models.EmailField()
    unix = models.IntegerField()

serializers.py

class UserStatsSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserStats
        fields = (
            'unix', 'user_email',
        )

views.py

class UserStatsViewSet(viewsets.ModelViewSet):
    serializer_class = UserStatsSerializer
    queryset = UserStats.objects.all()
    permission_classes = (IsAdminOrReadOnly,)
    http_method_names = ['get', 'patch', 'post']

    def get_queryset(self):
        queryset = self.queryset.filter(user=self.request.user)
        return queryset

    def create(self, validated_data):
        user_email = validated_data.data['user_email']
        user = get_user_model().objects.get(email=user_email)
        unix = validated_data.data['unix']

        object = UserStats.objects.create(user=user, unix=unix)

        return Response(status=status.HTTP_201_CREATED)

Edit:
That was kind a easy to solve. Code is updated and is working.