序列化后的结果不同取决于环境

时间:2016-12-13 08:33:58

标签: python django django-rest-framework

我发送来自rest web json表单和custom_answers字段的请求存在转换后的列表数据,但是当我使用ApiClient发送相同的数据时,custom_answers空列表。

print validated_data从restf web json表单创建序列化方法

{'custom_answers': [OrderedDict([('user', <SimpleLazyObject: <User: 123>>), ('question', <Question: Вопрос 2>), ('text', 'TExt')]), OrderedDict([('user', <SimpleLazyObject: <User: 123>>), ('question', <Question: Вопрос 1>), ('text', 'tes')])], 'poll': <Poll: Опрос 1>, 'user': <SimpleLazyObject: <User: 123>>}

print validated_data从test env

创建序列化方法
{'custom_answers': [], 'poll': <Poll: Опрос 1>, 'user': <User: 123>}

从测试环境打印序列化程序初始化数据:

<QueryDict: {'poll': ['1'], 'custom_answers': ["{'question': 2, 'text': 'TExt'}", "{'question': 1, 'text': 'tes'}"]}>

使用json数据从web打印序列化程序初始化数据:

{custom_answers': [{'text': 'TExt', 'question': 2}, {'text': 'tes', 'question': 1}], 'poll': 1}

抱歉我的英文。

serializers.py

class CustomUserAnswerSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(
        read_only=True,
        default=CurrentUserDefault()
    )

    class Meta:
        model = CustomUserAnswer
        fields = ('user', 'question', 'text')


class CompletedPollSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(
        read_only=True,
        default=CurrentUserDefault()
    )
    custom_answers = CustomUserAnswerSerializer(
        many=True, write_only=True, required=False      
    )

    class Meta:
        model = CompletedPoll
        fields = ('poll', 'user', 'custom_answers')

    def create(self, validated_data):
        print(validated_data)

models.py ---与模型无关的

class CompletedPoll(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='ended_polls'
    )
    poll = models.ForeignKey(Poll)
    ended_date = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('-ended_date',)
        unique_together = ('user', 'poll')


class CustomUserAnswer(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        related_name='custom_answers'
    )
    question = models.ForeignKey(
        Question,
        related_name='custom_answers'
    )
    text = models.CharField(
        verbose_name='Текст ответа',
        max_length=800
    )

    class Meta:
        unique_together = ('user', 'question')

tests.py

class ApiPollsTestCase(APITestCase):
    def setUp(self):
        call_command('loaddata', 'polls/fixtures/polls')

    self.user = User.objects.create(
        username='123',
        password='123',
        email='123@123.ru'
    )

    self.client = APIClient()
    self.client.credentials(
        HTTP_AUTHORIZATION='Token ' + self.user.auth_token.key
    )

    def test_complete_poll(self):
        data = {
            'poll': 1,
            'custom_answers': [
                {'question': 2, 'text': 'TExt'},
                {'question': 1, 'text': 'tes'}
            ]
        }

        response = self.client.post(reverse('api_v1:complete-poll'), data)
        print(CustomUserAnswer.objects.all(), response.data)
        self.assertEqual(response.status_code, 201)
        self.assertTrue(
            CompletedPoll.objects.filter(
                user=self.user, poll__id=data['poll']
            ).exists()
        )

1 个答案:

答案 0 :(得分:0)

您发送的数据的默认内容类型是不支持嵌套数据的html表单。

您需要明确提到您正在发送json数据:

response = self.client.post(reverse('api_v1:complete-poll'), data, format='json')