我有一个引用Django模型User的模型用户首选项。我一直收到错误:
IntegrityError: null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (dfac4cb7-0bdb-44e4-b951-c0c9386bf143, f, null)
尝试发布新的用户首选项时。我寄给帖子的数据是:
{
"user": "http://127.0.0.1:8000/user/4/",
"send_email": false
}
我的用户偏好模型是:
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)
我的用户偏好视图是:
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()
我的userpreference序列化程序是:
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')
有什么建议吗?
编辑:在我的视图中添加post方法为我解决了这个问题。在UserPreferenceList类中,我添加了:
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)
答案 0 :(得分:1)
这是因为这一行发生的事情:
user = models.OneToOneField(User, related_name="user_preference", on_delete=models.CASCADE, db_index=True)
在UserPreference
Model
中,当您指定该字段/关系时,您说的是User
必须存在外键。一个没有,所以你得到了那个错误。
在POST或create方法中,将user
指定为整数id
,因为它是主键。