完整性错误:“notification_type_id”列中的空值违反了非空约束

时间:2015-12-14 10:08:13

标签: django django-rest-framework

我不熟悉Django Rest Framework和Django。我有以下模型类:

currentApplication.EndDate.Value

我的Serializer和Viewsets如下:

class NotificationType(LogModel):
    name = models.CharField(max_length=300, verbose_name="Name")
    frequency = models.PositiveSmallIntegerField(
    choices=NotificationFrequency.CHOICES,
    verbose_name="notification_frequency")

    active = models.BooleanField(default=1)

class Meta:
    db_table = 'notificaiton_type'
    verbose_name = 'NotificationType'
    verbose_name_plural = 'NotificationTypes'
    ordering = ('-id',)

def __str__(self):
    return "{}{}".format(self.name, self.frequency)

@python_2_unicode_compatible
class Notification(LogModel):
    notification_type = models.ForeignKey(NotificationType)
    property_info = models.ForeignKey(PropertyInfo)
    description = models.TextField(verbose_name="Notification Description")
    action = models.TextField(blank=True, null=True)

class Meta:
    db_table = 'notification'
    verbose_name = 'Notification'
    verbose_name_plural = 'Notifications'
    ordering = ('-id',)

def __str__(self):
    return "{}".format(self.description)

views.py:

class NotificationTypeSerializer(serializers.ModelSerializer):

class Meta:
    model = NotificationType
    fields = ('name', 'frequency', 'active')


class NotificationSerializer(serializers.ModelSerializer):
    property_info = PropertyInfoSerializer(read_only=True)
    notification_type = NotificationTypeSerializer(read_only=True)

    class Meta:
        model = Notification

我的urls.py文件包含以下网址格式:

class NotificationCRUDView(generics.ListCreateAPIView):
    model = Notification
    serializer_class = serializers.Notification
    authentication_classes = (TokenAuthentication,)
    permission_classes = (IsAuthenticated,)

    def post(self, request, pk, property_id):  #
        serializer = serializers.NotificationSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

现在每当我尝试使用url路径进行POST调用时 / api / v1 / notification / pk / property_id {其中pk和property_id}作为url参数传递。我收到了上面提到的错误。 任何人都可以帮助我。 TIA。 :)

1 个答案:

答案 0 :(得分:2)

  

现在每当我尝试使用url path / api / v1 / notification / pk / property_id {其中pk和property_id}作为url参数传递时进行POST调用。

POST来电中,您不会在网址中传递数据。它必须作为请求体传递。

POST /api/v1/notifications/

请求正文:

{
  "property_info": "<id>",
  "property_type": "<id>"
}

ListCreateAPIView中,没有post方法,如果您想覆盖POST调用的视图,请使用def create(self, request):方法。

查看CreateModelMixin的实现[1]。

[1] https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py#L14-L23
[2] http://www.django-rest-framework.org/api-guide/generic-views/#listcreateapiview