gpt4 book ai didi

Django请求框架 'ManyRelatedField'对象在修改get_fields中的查询集时没有属性 'queryset'

转载 作者:行者123 更新时间:2023-12-03 02:52:00 25 4
gpt4 key购买 nike

我在 StorySerializer 中的 GET/api/stories/169/ 上收到以下错误,如下评论中所述:

AttributeError at /api/stories/169/
'ManyRelatedField' object has no attribute 'queryset'

在检查该对象后,我发现如果我更改该行...

fields['feature'].queryset = fields['feature'].queryset.filter(user=user)

fields['photos'].child_relation.queryset = fields['photos'].child_relation.queryset.filter(user=user)

...似乎有效。但这种方法没有记录,我确信这不是正确的方法。

我有这些模型:

class Story(CommonInfo):
user = models.ForeignKey(User)
text = models.TextField(max_length=5000,blank=True)
feature = models.ForeignKey("Feature", blank=True, null=True)
tags = models.ManyToManyField("Tag")

class Feature(CommonInfo):
user = models.ForeignKey(User)
name = models.CharField(max_length=50)

class Photo(CommonInfo):
user = models.ForeignKey(User)
image = ImageField(upload_to='photos')
story = models.ForeignKey("Story", blank=True, null=True, related_name='photos', on_delete=models.SET_NULL)

还有一个StorySerializer:

class StorySerializer(serializers.HyperlinkedModelSerializer):
user = serializers.CharField(read_only=True)
comments = serializers.HyperlinkedRelatedField(read_only=True, view_name='comment-detail', many=True)

def get_fields(self, *args, **kwargs):
user = self.context['request'].user
fields = super(StorySerializer, self).get_fields(*args, **kwargs)

## Restrict the options that the user can pick to the Features
## and Photos that they own
# This line works:
fields['feature'].queryset = fields['feature'].queryset.filter(user=user)

# This line throws the error:
fields['photos'].queryset = fields['photos'].queryset.filter(user=user)

return fields

class Meta:
model = Story
fields = ('url', 'user', 'text', 'comments', 'photos', 'feature', 'tags')

我做错了什么?我觉得这与 ForeignKey 关系的方向有关。

最佳答案

两个要点。

  1. 当从用户的 View 中过滤查询集时,所有外键对象检索将仅生成特定用户的对象。因此无需在 get_fields 内过滤用户。

    class StoryList(generics.ListAPIView):
    serializer_class = StorySerializer

    def get_queryset(self):
    # consider there is login check before code is reaching here
    # since this filtered by the user and any susbquent
    # foreign key objects will belong only to this user
    return Story.objects.filter(user=self.request.user)
  2. 一旦对用户进行过滤,您就可以使用另一个序列化程序或 SerializerMethodField 来相应地构造数据。下面的代码应该适用于您的情况。

     class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
    # Allow only url and id
    fields = ['id', 'url']
    extra_kwargs = {'url': {'view_name': 'user-detail'}}

    class FeatureSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
    fields = ['id', 'url']
    extra_kwargs = {'url': {'view_name': 'feature-detail'}}

    class PhotoSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
    fields = ['id', 'url']
    extra_kwargs = {'url': {'view_name': 'photo-detail'}}

    class StorySerializer(serializers.HyperlinkedModelSerializer):
    user = UserSerializer(read_only=True)
    comments = serializers.HyperlinkedRelatedField(read_only=True,
    view_name='comment-detail', many=True)
    # this work because of related names
    features = FeatureSerializers(many=True)
    photos = PhotoSerializers(many=True)
    # add tags serializer as well
    text = serializers.CharField()

    class Meta:
    fields = ['id', 'users', 'photos', 'features', ...]

关于Django请求框架 'ManyRelatedField'对象在修改get_fields中的查询集时没有属性 'queryset',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29281149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com