在ModelSerializer中,self.context没有请求,如何获取它

时间:2018-02-02 10:27:14

标签: django django-rest-framework

我的序列化程序类是:

class NakshatraDateSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(read_only=True)
    is_note_present = serializers.SerializerMethodField(read_only=True)

    def get_is_note_present(self, nakshatra_date ):
        user = None
        request = self.context.get("request")

        print (str(request))

        if request and hasattr(request, "user"):
            user = request.user
        # user = serializers.SerializerMethodField('_user')
        if user is None:
            logging.error("user is none")
            return False
        try:
            nakshatra_date_note = Notes.objects.all().get(nakshatra_date=nakshatra_date, created_by=user)
        except ObjectDoesNotExist:
            nakshatra_date_note = None

        if nakshatra_date_note is None:
            logging.error("no note present for this nakshatra date")
            return False

        logging.error(str(nakshatra_date_note))
        return True


date = serializers.DateField(
        required=True,
        error_messages={
            "date": "Nakshatra for date already present",
        },
        validators=[UniqueValidator(queryset=NakshatraDate.objects.all(), message="Nakshatra for date already present

")]
)

class Meta:
    model = NakshatraDate
    fields = (
    'id',  'is_note_present', 'date', 'updated', 'created')

vewclass是:

class NakshatraDateViewSet(viewsets.ModelViewSet):
"""
    Nakshatra dates
"""
    permission_classes = (AllowAny,)
    queryset = NakshatraDate.objects.all()
    serializer_class = NakshatraDateSerializer
    pagination_class = LargeResultsSetPagination
    filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)
    filter_class = NakshatraDateFilter

    def filter_queryset(self, queryset):
        queryset = super(NakshatraDateViewSet, self).filter_queryset(queryset)
        return queryset.order_by('-id')

    def perform_create(self, serializer):
        serializer.save()

我正在努力设定价值' True'如果特定日期存在注释,则在变量is_note_present中。否则'错误'。但我无法在self.context中获取请求对象。

class Notes(models.Model):
    date = models.DateField(null=False)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True, editable=False)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='notes', on_delete=models.CASCADE)

我尝试了各种方式来获取请求。其中一些是def get_serializer_context(self): return {'request': self.request} 和treien上下文(context = {' request':request})在modelviewset中使用serialize_class变量 我仍然无法在self.context中获取请求

1 个答案:

答案 0 :(得分:1)

你的观点应该是这样的。

class NakshatraDateViewSet(viewsets.ModelViewSet):
    """
    Nakshatra dates
    """
    permission_classes = (AllowAny,)
    serializer_class = NakshatraDateSerializer
    pagination_class = LargeResultsSetPagination
    filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)
    filter_class = NakshatraDateFilter

    def get_queryset(self, queryset):
        queryset = NakshatraDate.objects.all()
        return queryset.order_by('-id')

    def get_serializer_context(self):
        return {'request': self.request}

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(data=serializer.data)
        return Response(status=status.HTTP_400_BAD_REQUEST) 

您可以进一步了解viewsets here