Django HyperlinkedRelatedField read_only False给出queryset错误

时间:2019-01-16 21:32:50

标签: django django-rest-framework

狗模型的字段为“猫”

class Dog(models.Model):
    ...
    cat = models.ForeignKey(Cat)
    ...

class CatSerializer(serializers.HyperlinkedModelSerializer):      
    class Meta:
        model = Cat
        # Replace ID with SLUG in urls
        lookup_field = 'slug'
        fields = ('url', 'slug')
        extra_kwargs = {
            'url': {'lookup_field': 'slug'}
        }

class DogSerializer(serializers.HyperlinkedModelSerializer):
    cat= serializers.HyperlinkedRelatedField(
        view_name='cat-detail',
        lookup_field='slug',
        many=False,
        read_only=True
    )
    class Meta:
        model = Dog
        fields = ('url', 'slug', 'cat')
        lookup_field = 'slug'
        extra_kwargs = {
           'url': {'lookup_field': 'slug'}
        }

class CatViewSet(viewsets.ModelViewSet):
    def get_serializer_context(self):
        context = super().get_serializer_context()
        context['slug'] = self.kwargs.get('slug')
        return context
    queryset = Cat.objects.all()
    serializer_class = CatSerializer
    lookup_field = 'slug'

class DogViewSet(viewsets.ModelViewSet):
    queryset = Dog.objects.all()
    lookup_field = 'slug'
    serializer_class = DogSerializer

router = routers.DefaultRouter()
router.register(r'cats', rest_views.CatViewSet)
router.register(r'dogs', rest_views.DogViewSet)

如何设置:

read_only=False

将其设置为False时出现的错误是:

  

“关系字段必须提供queryset自变量,   AssertionError:关系字段必须提供queryset参数,覆盖get_queryset或设置read_only = True

1 个答案:

答案 0 :(得分:0)

cat= serializers.HyperlinkedRelatedField(
    view_name='cat-detail',
    lookup_field='slug',
    many=False,
    read_only=False,
    queryset=Cat.objects.all()
)

这很好用。