Dango中有两个模型user和blog,blog含有外键字段通过tofield指向了user模型的userrname字段,请问前端如何发送数据格式,通过,modelviewset保存数据?
时间: 2024-09-17 21:00:38 浏览: 46
在Django中,如果你使用ModelViewSet(基于Rest_framework库)来处理用户(User)和博客(Blog)的数据操作,前端需要按照RESTful API的标准发送数据。对于包含外键关联的情况,你需要提供以下格式的数据:
1. 用户模型(User)的POST请求通常会包含`username`字段,如果创建新的Blog,`author`字段可能会指定用户的ID或用户名。例如:
```json
{
"title": "My First Blog",
"content": "This is my first blog post.",
"author": { // 如果是用户ID
"id": <user_id>
} 或者 {
"author": { // 如果是用户名
"username": "<user_username>"
}
}
```
2. 更新或创建Blog时,如果已经存在一个User实例并希望关联,可以传递`author`字段为该User的ID或完整的User对象:
```json
{
"id": <blog_id>, // 要更新的Blog ID
"title": "Updated Title",
"author": {
"username": "<user_username>"
}
}
```
当通过ModelViewSet保存数据时,ViewSet会自动将这些数据映射到对应的数据库模型,处理外键关联。
阅读全文
相关推荐

















