【发布时间】:2015-05-30 15:04:28
【问题描述】:
我在 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 关系的方向有关。
【问题讨论】:
-
不确定,但可能是故事模型与照片模型之间没有关系,但照片与故事之间存在关系
-
我也遇到了同样的问题。在 DRF 2.0 中,该字段没有子关系,因此您可以只使用
field.queryset而不是field.child_relation.queryset。现在的问题是,如果 child_relation 有可能嵌套,那么一个好的解决方案会很好。 -
哦,没关系,它似乎没有无限嵌套,这是一个错误。尽管如此,一些官方的推理还是不错的。
标签: django django-rest-framework