Home > Mobile >  Cannot resolve keyword 'author' into field
Cannot resolve keyword 'author' into field

Time:10-11

Here is the issue.I am trying to delete the tags related to my model. I can create them but whenever i try to use HTTP DELETE on ExampleModelTags, i face with the following issue.

Error: Cannot resolve keyword 'author' into field. Choices are: id, examplemodel, examplemodel_id, tag, timestamp

I can't understand what is the issue, i can create them so the algorithm works. The tags can connect to their parent model . But whenever i try to do HTTP DELETE on ExampleModelTags, i get that issue. Where is the problem that i don't see?

Model.py

class ExampleModelTag(models.Model):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    tag = models.CharField(max_length=35,null=True,blank=True)
    examplemodel = models.ForeignKey(ExampleModel, on_delete=models.CASCADE,null=True,blank=True, related_name='examplemodeltags')
    timestamp = models.DateTimeField(auto_now_add=True)


class ExampleModel(models.Model):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    author = models.ForeignKey(User, on_delete=models.CASCADE,null=True,related_name='examplemodels')
    examplemodel = models.CharField(unique=False,max_length=100,null=True,blank=True)
    timestamp = models.DateTimeField(unique=False,auto_now_add=True)

Serializer.py

class ExampleModelTagSerializer(serializers.ModelSerializer):

    class Meta:
        model = ExampleModelTag
        fields = ("id","examplemodel","tag","timestamp")

    def validate(self, attrs):
        attrs = super().validate(attrs)
        if attrs['examplemodel'].author.id != self.context['request'].user.pk:
            raise ValidationError('Unauthorized Request')
        return attrs


class ExampleModelSerializer(serializers.ModelSerializer): 
    examplemodeltags_set = ExampleModelTagSerializer(source='examplemodeltags',required=False,many=True)

    class Meta:
        model = ExampleModel
        fields = ("id","author","examplemodel","examplemodeltags_set","timestamp")

    def validate(self, attrs):
        attrs = super().validate(attrs)
        if attrs['author'].id != self.context['request'].user.pk:
            raise ValidationError('Unauthorized Request')
        return attrs

Views.py

class ExampleModelViewSet(viewsets.ModelViewSet):
    permission_classes = (IsAuthenticated,)
    queryset = ExampleModel.objects.all().order_by('-timestamp')
    serializer_class = ExampleModelSerializer
    filter_backends = [UserFilterBackend]

class ExampleModelTagViewSet(viewsets.ModelViewSet):
    permission_classes = (IsAuthenticated,)
    queryset = ExampleModelTag.objects.all()
    serializer_class = ExampleModelTagSerializer
    filter_backends = [UserFilterBackend]

Filters.py

class UserFilterBackend(filters.BaseFilterBackend):
    
    def filter_queryset(self, request, queryset, view):
        return queryset.filter(
            author=request.user
        )

CodePudding user response:

You can not use the UserFilterBackend on the ExampleModelTagViewSet, since an ExampleModelTag has no author field. You thus should rewrite the ExampleModelTagViewSet to:

class ExampleModelTagViewSet(viewsets.ModelViewSet):
    # ⋮
    filter_backends = []  # ← UserFilterBackend not applicable

If you want to fetch ExampleModelTags for which an ExampleModel exists that links to that ExampleModelTag record, and has as author the logged in user, you can specify this with:

class ExampleModelAuthorBackend(filters.BaseFilterBackend):
    
    def filter_queryset(self, request, queryset, view):
        return queryset.filter(
            examplemodel__author=request.user
        )

and then use that one to filter the ExampleModelTags:

class ExampleModelTagViewSet(viewsets.ModelViewSet):
    # ⋮
    filter_backends = [ExampleModelAuthorBackend]

CodePudding user response:

class UserFilterBackend(filters.BaseFilterBackend):
    
    def filter_queryset(self, request, queryset, view):
        return queryset.filter(
            examplemodel__author=request.user
        )
  • Related