Django序列化程序在创建时返回空字典

z9smfwbn  于 2022-11-26  发布在  Go
关注(0)|答案(1)|浏览(131)

我有一个基本上连接两个不同用户的模型:

class Couple(models.Model):
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False)

    user1 = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        null=True,
        blank=False,
        related_name="user1"
    )

    user2 = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        null=True,
        blank=False,
        related_name="user2"
    )

    def __str__(self):
        return str(self.id)

接下来我做的是创建一个Serializer,其中user 1邀请user 2创建一对。我想通过编写user 2的电子邮件地址来实现这一点:

class CreateCoupleSerializer(serializers.Serializer):

    partner_email = serializers.EmailField(write_only=True, max_length=250,
                                           required=True)

    def create(self, validated_data):
        partner_email = validated_data['partner_email']
        try:
            partner = User.objects.get(email=partner_email)
        except Exception:
            partner = None

        if not partner:
            raise serializers.ValidationError(
                {"details": 'User does not exist'})

        if partner.couple_id:
            raise serializers.ValidationError(
                {"details": 'User is already assigned to a couple'})

        user = self.context['request'].user
        couple = Couple.objects.create(user1=user, user2=partner)

        user.couple_id = couple.id
        partner.couple_id = couple.id
        user.save()
        partner.save()

        return couple

而这就是我的看法:

class CreateCoupleView(generics.CreateAPIView):
    serializer_class = CreateCoupleSerializer
    queryset = Couple.objects.all()

通过测试,我可以看到创建了Couple,这很好!但是,在我的身体React中,我得到了一个空的字典,而不是新的couple示例。

我的问题是为什么会这样

**附加问题:**什么时候应该在串行器端的def create()中创建逻辑,而不是在视图端的def create()中创建逻辑?

先谢谢你了。

pb3skfrl

pb3skfrl1#

我通过将其替换为serializers.ModelSerializer并如下定义read_only_fields来修复此问题:

class CreateCoupleSerializer(serializers.ModelSerializer):

partner_email = serializers.EmailField(write_only=True, max_length=250,
                                       required=True)

class Meta:
    model = Couple
    fields = '__all__'
    read_only_fields = ('user1', 'user2', )

相关问题