在Django REST框架中发布带有字段的数据。

huangapple go评论78阅读模式
英文:

Post data with field in django REST framework

问题

I am designing my API using serializers.ModelSerializer and viewsets.ModelViewSet. I can post the foreignKey value using the id, but I want to post it using the name. Here is an example of what I mean:

我正在使用serializers.ModelSerializerviewsets.ModelViewSet来设计我的API。我可以使用id来发布foreignKey值,但我想使用name来发布它。这是我所说的示例:

I can post on this:

我可以这样发布:

curl --request POST \
     --url http://127.0.0.1:8000/api/book/ \
     --header 'Content-Type: multipart/form-data' \
     --form author=1 \
     --form name=MY_BOOK

but I want do this:

但我想要这样做:

curl --request POST \
     --url http://127.0.0.1:8000/api/book/ \
     --header 'Content-Type: multipart/form-data' \
     --form author=AUTHOR_NAME \
     --form name=MY_BOOK

I have tried to use to_internal_value, and it works, but I want to know if there is a better plan:

我尝试使用to_internal_value,它有效,但我想知道是否有更好的方案:

def to_internal_value(self, data):
        data = data.copy()
        data['author'] = get_object_or_404(Author, name=data['author']).id
        return super().to_internal_value(data)

Here in my code:

这是我的代码中的部分:

class Author(models.Model):
    name = models.CharField(max_length=128, unique=True)

    def __str__(self):
        return self.name


class Book(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    name = models.CharField(max_length=128, unique=True)

    def __str__(self):
        return self.name

class AuthorSerializer(serializers.ModelSerializer):

    class Meta:
        model = Author
        fields = '__all__'

class BookSerializer(serializers.ModelSerializer):

    class Meta:
        model = Book
        fields = '__all__'

    def to_internal_value(self, data):
        data = data.copy()
        data['author'] = get_object_or_404(Author, name=data['author']).id
        return super().to_internal_value(data)

Any help or explanation is welcome! Thank you.

欢迎提供任何帮助或解释!谢谢。

英文:

I am designing my API using serializers.ModelSerializer and viewsets.ModelViewSet. I can post the foreignKey value using the id, but I want to post it using the name. Here is an example of what I mean:

I can post on this:

curl --request POST \
     --url http://127.0.0.1:8000/api/book/ \
     --header 'Content-Type: multipart/form-data' \
     --form author=1 \
     --form name=MY_BOOK

but I want do this:

curl --request POST \
     --url http://127.0.0.1:8000/api/book/ \
     --header 'Content-Type: multipart/form-data' \
     --form author=AUTHOR_NAME \
     --form name=MY_BOOK

I have try use to_internal_value it's work, but I think it want to know is there a better plan:

def to_internal_value(self, data):
        data = data.copy()
        data['author'] = get_object_or_404(Author, name=data['author']).id
        return super().to_internal_value(data) 

Here in my code:

class Author(models.Model):
    name = models.CharField(max_length=128, unique=True)
    
    def __str__(self):
        return self.name


class Book(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    name = models.CharField(max_length=128, unique=True)
    
    def __str__(self):
        return self.name

class AuthorSerializer(serializers.ModelSerializer):

    class Meta:
        model = Author
        fields = '__all__'

class BookSerializer(serializers.ModelSerializer):

    class Meta:
        model = Book
    fields = '__all__'

    def to_internal_value(self, data):
        data = data.copy()
        data['author'] = get_object_or_404(Author, name=data['author']).id
        return super().to_internal_value(data) 

Any help or explanation is welcome! Thank you.

答案1

得分: 2

你可以使用SlugRelatedField来实现这个。像这样定义BookSerializer

class BookSerializer(serializers.ModelSerializer):
    author = serializers.SlugRelatedField(slug_field="name", queryset=Author.objects.all())

    class Meta:
        model = Book
        fields = '__all__'
英文:

You can do this with SlugRelatedField. Define BookSerializer like this:

class BookSerializer(serializers.ModelSerializer):
    author = serializers.SlugRelatedField(slug_field="name", queryset=Author.objects.all())

    class Meta:
        model = Book
        fields = '__all__'

huangapple
  • 本文由 发表于 2023年5月10日 11:04:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76214622.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定