Вопрос:

Django null value in column "user_id" violates not-null constraint

django post django-rest-framework constraints

2202 просмотра

1 ответ

554 Репутация автора

I have a model userpreference that references Django model User. I keep getting error: IntegrityError: null value in column "user_id" violates not-null constraint DETAIL: Failing row contains (dfac4cb7-0bdb-44e4-b951-c0c9386bf143, f, null) when trying to post a new userpreference. the data I sent for post is:

{
    "user": "http://127.0.0.1:8000/user/4/",
    "send_email": false
}

my userpreference model is:

import uuid
from django.db import models
from django.contrib.auth.models import User


class UserPreference(models.Model):
    class Meta:
        app_label = 'my_app'
        permissions = (
            ('view_userpreference', 'View User Preference'),
        )

    uuid = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)
    user = models.OneToOneField(User, related_name="user_preference", on_delete=models.CASCADE, db_index=True)
    send_email = models.BooleanField(default=True, db_index=True)


    def __unicode__(self):
        return u"<UserPreference {0} {1}>".format(str(self.uuid), self.user.id)

my userpreference view is:

class UserPreferenceList(generics.ListCreateAPIView):
    model = UserPreference
    permission_classes = (permissions.IsAuthenticated, CustomObjectPermissions)
    serializer_class = UserPreferenceListSerializer
    queryset = UserPreference.objects.all()


class UserPreferenceDetail(generics.RetrieveUpdateDestroyAPIView):
    model = UserPreference
    permission_classes = (permissions.IsAuthenticated, CustomObjectPermissions)
    serializer_class = UserPreferenceSerializer
    queryset = UserPreference.objects.all()

and my userpreference serializer is:

class UserPreferenceSerializer(serializers.HyperlinkedModelSerializer):
    user = serializers.HyperlinkedRelatedField(view_name='user-detail', read_only=True, lookup_field="id", lookup_url_kwarg="pk")

    class Meta:
        model = UserPreference
        fields = ('url',
                  'user',
                  'send_email')


class UserPreferenceListSerializer(serializers.HyperlinkedModelSerializer):
    user = serializers.HyperlinkedRelatedField(view_name='user-detail', read_only=True, lookup_field="id", lookup_url_kwarg="pk")

    class Meta:
        model = UserPreference
        fields = ('url',
                  'user',
                  'send_email')

Any suggestions?

Edit: Adding post method to my view solved this problem for me. In UserPreferenceList class, I added:

def post(self, request, *args, **kwargs):
    user_url = request.data.get('user', None)
    if user_url:
        try:
            path = urlparse.urlparse(user_url).path
            match = resolve(path)
            user_pk = match.kwargs.get('pk')
        except (Resolver404, User.DoesNotExist) as e:
            raise CustomAPIException("You need to send the url of a User to create its UserPreference.", status=status.HTTP_400_BAD_REQUEST)
    else:
        raise CustomAPIException("You need to identify a User to create its UserPreference.", status=status.HTTP_400_BAD_REQUEST)

    userpreference_obj = UserPreference(user_id=user_pk, send_email=request.data.get('send_email', False))
    userpreference_obj.save()
    d = UserPreferenceSerializer(userpreference_obj, context={'request': request}).data
    return Response(d, status=status.HTTP_201_CREATED)
Автор: Nicky Mirfallah Источник Размещён: 22.08.2016 09:04

Ответы (1)


1 плюс

10618 Репутация автора

Решение

That is happening because of this line here:

user = models.OneToOneField(User, related_name="user_preference", on_delete=models.CASCADE, db_index=True)

In the UserPreference Model, when you specify that field / relationship, you're saying that a Foreign Key must exist for the User. One does not, so you're getting that error.

In you POST, or create method, specify the user as a Integer id since it is a primary key.

Автор: Aaron Lelevier Размещён: 22.08.2016 10:41
Вопросы из категории :
32x32