我已经开始学习如何将Django REST Framework与React一起使用,我有一个快速的问题。我做了一个表格,分别使用CreateAPIView
和UpdateAPIView
创建/更新项目。但是,如果列表来自我的一个模型中的变量,如何获取内容填充我的<select>
字段?
from model_utils import Choices
class Author(models.Model):
GENDER = Choices('male', 'female', "I don't know really") # How do I get this?
gender = models.CharField(max_length=10, choices=GENDER)
Author.GENDER
的 serializer 和 views 会是什么样,因为它不是模型?
此刻,这就是我现在拥有的。
Django(我想这与众不同)。
# Serializer.
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = Author
fields = ('id', 'gender')
# View
class AuthorUpdateView(UpdateAPIView):
queryset = Author.objects.filter(deleted_at__isnull=True)
serializer_class = AuthorSerializer
反应。
componentDidMount() {
const pk = this.props.match.params.pk
axios.get(`http://localhost:8000/api/authors/${pk}`)
.then(response => {
const pk = response.data.id
const gender = response.data.gender
this.setState({gender})
})
.catch(err => console.log(err))
}
我对使用DRF时可能遇到的任何方向或概念持开放态度,因此我也可以从中学习如何使用它。
答案 0 :(得分:0)
使用viewset组合一组相关视图(列出,创建,更新)的逻辑
class AuthorViewSet(ModelViewSet):
queryset = Author.objects.filter(deleted_at__isnull=True)
serializer_class = AuthorSerializer
发出OPTIONS
请求以获取资源的元数据,包括gender
字段的有效选择列表
请求
OPTIONS /api/authors/
回复
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"name": "Author List",
"parses": [
"application/json",
"application/x-www-form-urlencoded",
"multipart/form-data"
],
"actions": {
"POST": {
"id": {
"type": "integer",
"required": false,
"read_only": true,
"label": "Id"
},
"gender": {
"type": "choice",
"required": true,
"read_only": false,
"label": "Gender",
"choices": [
{
"value": "male",
"display_name": "male"
},
{
"value": "female",
"display_name": "female"
},
{
"value": "I don't know really",
"display_name": "I don't know really"
}
]
}
}
}
}
答案 1 :(得分:0)
正如我在评论中提到的那样,您可以创建一个简单的视图以返回选择。
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view()
def foo_view(request):
choices = [i[0] for i in Author.GENDER]
return Response(choices)