如何使用PrimaryKeyRelatedField更新多对多关系的类别

时间:2015-06-12 11:17:27

标签: python django django-rest-framework

Django Rest Framework有一个PrimaryKeyRelatedField,其中列出了$ awk 's=$1~/^\|2/{gsub(/^\||\|$/,""); gsub(/\|/,",")}s' file 200965 ,18604165309338 ,18604165309387 ,2012 ,6100202749 ,AAA2778202 201163 ,10740000822407 ,10740000822606 ,2012 ,6100202749 ,AAA2778202 201232 ,18604177741067 ,18604177741366 ,2012 ,6100202749 ,AAA2778202 201295 ,18604221522337 ,18604221523836 ,2012 ,6100202749 ,AAA2778202 201480 ,18604113309952 ,18604113310131 ,2012 ,6100202749 ,AAA2778202 201781 ,18604199150436 ,18604199150835 ,2012 ,6100202749 ,AAA2778202 201480 ,6001400030046472 ,6001400030046771 ,2012 ,6100202520 ,AAA2777953 202853 ,6001700000180323 ,6001700000180722 ,2012 ,6100202520 ,AAA2777953 与类别的关系中的ID ...

many-to-many

我想覆盖class CatalogueItemsSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='catalogue_item_detail') name = serializers.CharField(min_length=2, max_length=60) categories = serializers.PrimaryKeyRelatedField(many=True, read_only=True) 在类别字段中获取大量已发布的ID(传统上DRF希望我发送URL' s)。

JSON POST:

create()

Serializer Create:

{
"name": "test",
"categories": [1,2]
}

我遇到的问题是def create(self, validated_data): categories = validated_data.pop('categories', None) print(categories) # This shows and empty/None even when ID are posted! 上面是空的,我假设categories设置为PrimaryKeyRelatedField,但 HAS 依据DRF。

我的问题是......如何使用read_only=TruePrimaryKeyRelatedField一起获取我提交的ID列表?

我可以使用validated_data.pop但这很讨厌,需要我把它变成一个列表+其他东西。

1 个答案:

答案 0 :(得分:1)

对于遇到此问题的其他人,我找到了一个允许PrimaryKeyRelatedField可读/写的解决方案。只需添加queryset

即可
categories = serializers.PrimaryKeyRelatedField(many=True, queryset=Category.objects.all())

它仍将过滤正确的关系,这有点令人困惑。