Django rest-framework如何序列化对象/外键

时间:2015-03-12 12:23:53

标签: python django django-rest-framework

我有Django Rest Framework的问题。 我有以下代码:

serializers.py

class TextSerializer(serializers.ModelSerializer):
    class Meta:
        model = Text
        fields = ('title', 'project', 'content')

    def create(self, validated_data):
        return Text.objects.create(**validated_data)

views.py

@csrf_exempt        
def text_view_set(request, project_id):
    project = get_object_or_404(Project, pk=project_id)

    if request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = TextSerializer(data=data)
        # How to put project in serializer to is_valid() return True?
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=status.HTTP_201_CREATED)
        return JSONResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)   

my_command.py

def handle(self, *args, **options):
        text = u'Lorem ipsum dolor sit amet, deseruisse voluptatum est cu, ea elit tation delicatissimi per. Decore soleat pri at.'
        url = u'http://localhost:8080/text/4/'

        params = { 'title' : u'Hello World', 'content': text.encode('utf8'), }
        req = requests.post(url, data=json.dumps(params), headers={"Content-Type": "application/json"})

因此,结果是错误的请求错误(400),因为is_valid()方法返回False。没关系。字段“项目”不在数据对象序列化中。

但是,如何在View或Model方法中插入此值? 我不想在params中传递这个值(项目),因为它已经在URL中了:

        url = u'http://localhost:8080/text/4/'

1 个答案:

答案 0 :(得分:0)

怎么样......

data = JSONParser().parse(request)
data.update({'pk': project_id})