针对特定用户的Django-rest保存模型

时间:2017-07-22 14:18:31

标签: django django-rest-framework

我有一个将用户作为外键的模型:

class Task(models.Model):
    user = models.ForeignKey(User)
    what_task = models.CharField(max_length=100, )

    #This helps to print in admin interface
    def __str__(self):
        return u"%s" % (self.what_task)

它的序列化器:

class TaskSerializer(serializers.ModelSerializer):
    steps = StepSerializer(many=True)
    class Meta:
        model = Task
        fields = '__all__'


    def create(self, validated_data):
        steps_data = validated_data.pop('steps')
        task = Task.objects.create(**validated_data)
        for step_data in steps_data:
            Step.objects.create(task=task, **step_data)
        return task 

在我看来,我有一个处理GETPOST请求的函数。 GET是正确的,它返回给我特定用户的所有任务 - 我使用request.user.id

我不确定我的POST,在这种情况下如何针对特定用户保存任务:

@api_view(['GET', 'POST'])
def task_list(request):
    """
    List all tasks, or create a new task.
    """
    if request.method == 'GET':
        tasks = Task.objects.filter(user=request.user.id)
        serializer = TaskSerializer(tasks, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = TaskSerializer(data=request.data)
        print(request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(
                serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我必须在序列化程序或视图中进行更改吗?

1 个答案:

答案 0 :(得分:1)

改变模型,

user = models.ForeignKey(User, blank=True)

然后,迁移您的更改。

然后,在你的观点中,

if serializer.is_valid():
    serializer.save(user=request.user)