django 为什么我不能添加对象到字段rest_framework

8hhllhi2  于 2023-01-27  发布在  Go
关注(0)|答案(1)|浏览(136)

我想使用rest_framework序列化器添加一些对象,但是我从序列化器得到这个错误。我看到一些人有相同的错误,但是我不知道如何在我的情况下修复它。

{
    "user": [
        "Incorrect type. Expected pk value, received str."
    ]
}

这是我的模特

class UserData(AbstractUser):

    username = None
    name = models.CharField(max_length=100, unique=True)
    email = models.EmailField(max_length=100, unique=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    pseudo = models.CharField(max_length=200,unique=True)
    hashtag = models.CharField(max_length=200, unique=True)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    
    objects = UserManager()
    
    USERNAME_FIELD = "pseudo"
    REQUIRED_FIELDS = ['name','hashtag','email']

    def __str__(self):
        return self.name

class Pebbles(models.Model):
    image = models.CharField(max_length=200)
    user = models.ForeignKey(UserData, related_name="pebbles",on_delete=models.CASCADE)

    class Meta():
        unique_together = ["id","user"]

我可以从那个Angular 得到一张鹅卵石的清单。

class PebblesView(generics.ListCreateAPIView):
    permission_classes = [IsAuthenticated]
    authentication_classes = [JWTAuthentication]
    serializer_class = PebblesSerializer

    def get_queryset(self):
        return Pebbles.objects.all()
    
    def create(self, request):
        serializer = PebblesSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

我可以用我的UserSerializer注册一个用户。我也有同样的pebble逻辑,但它不起作用。在Django shell中,我可以像这样创建pebble。

class UserSerializer(serializers.ModelSerializer):
    pebbles = serializers.StringRelatedField(many=True)

    class Meta:
        model = UserData
        fields = ["id", "pseudo", "hashtag","email", "name", "password","pebbles"]

    def create(self, validated_data):
        user = UserData.objects.create(
            email=validated_data['email'],
            name=validated_data['name'],
            pseudo=validated_data['pseudo'],
            hashtag=validated_data['hashtag']
        )
        user.set_password(validated_data['password'])
        user.save()
        return user

class PebblesSerializer(serializers.ModelSerializer):

    class Meta:
        model = Pebbles
        fields = ["id","image","user"]

    def create(self, request):
        pebbles = Pebbles.objects.create(
            image=request['image'],
            user=UserData.objects.get(pseudo=request['user'])
        )
        pebbles.save()
        return pebbles

谁能给我个提示?

qqrboqgw

qqrboqgw1#

我不明白Django rest框架在自动化方面走了这么远。

request["user"]

它已经包含了UserData对象,所以不需要搜索它。而且我确实犯了一个错误,用伪字段代替了id。

相关问题