如何通过Postman或Rest API在Django中向MySQL插入JSON数据?
Hey there! Let's troubleshoot why your API isn't inserting JSON data into MySQL. Looking at your code, you're mixing raw SQL operations with Django REST Framework (DRF) serializer logic, plus there are a few syntax and logical missteps that are blocking the data insertion. Let's break this down:
Key Problems in Your Code
- Wrong way to access request data: You’re using
request.json, but DRF doesn’t expose this property. The correct method to get JSON payloads from a POST request isrequest.data. This is likely causing a silent error right at the start. - Redundant & conflicting database logic: You’re trying both raw SQL inserts and DRF serializer saves. Not only is this redundant, but your raw SQL code doesn’t show proper database connection setup (no imports for
mysql, no connection cleanup) which would lead to errors or resource leaks. - Indentation & logical flow issues: The
return Response(serializer.errors...)line is incorrectly indented—it would run regardless of whether the serializer is valid, breaking your error handling. - Model vs. table mismatch: Your model is named
fetchdata, but you’re inserting intotbl_uservia raw SQL. This suggests either your model isn’t mapped to the correct table, or you’re targeting the wrong table entirely.
Corrected Code (Using DRF Best Practices)
Since you’re already using DRF serializers and Django models, you don’t need raw SQL at all—DRF handles the database interactions cleanly. Here’s a simplified, working version:
from django.shortcuts import render, redirect from rest_framework.decorators import api_view from rest_framework.response import Response from .models import fetchdata # Rename this to User for clarity if it's a user table! from .serializers import fetchdataSerializers from rest_framework import status @api_view(['GET','POST']) def index(request): if request.method == 'POST': # Use request.data to grab the JSON payload from Postman serializer = fetchdataSerializers(data=request.data) # Validate the incoming data first if serializer.is_valid(): serializer.save() # DRF handles inserting to the database via your model return Response({'message': 'User added successfully!'}, status=status.HTTP_201_CREATED) # If validation fails, send back the error details return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # Handle GET requests (return all existing records, for example) elif request.method == 'GET': all_records = fetchdata.objects.all() serializer = fetchdataSerializers(all_records, many=True) return Response(serializer.data)
Additional Checks to Ensure Success
Map your model to the correct database table:
If yourfetchdatamodel should point totbl_user, add aMetaclass to your model to specify the table name:class fetchdata(models.Model): user_name = models.CharField(max_length=100) user_email = models.EmailField(unique=True) user_password = models.CharField(max_length=100) class Meta: db_table = 'tbl_user' # Explicitly link to your existing MySQL tableAlign serializer fields with your JSON payload:
Make sure your serializer matches the keys you’re sending from Postman. If you’re sendingname,email,pwdbut your model usesuser_name,user_email,user_password, add field mappings:from rest_framework import serializers from .models import fetchdata class fetchdataSerializers(serializers.ModelSerializer): name = serializers.CharField(source='user_name') email = serializers.EmailField(source='user_email') pwd = serializers.CharField(source='user_password') class Meta: model = fetchdata fields = ['name', 'email', 'pwd']Postman request setup:
- Send a
POSTrequest to your API endpoint (e.g.,http://localhost:8000/your-endpoint/) - Set the request header
Content-Type: application/json - Use a valid JSON body like this:
{ "name": "John Doe", "email": "john@example.com", "pwd": "securepass123" }
- Send a
Verify MySQL database configuration:
Double-check yoursettings.pyto ensure Django can connect to MySQL:DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'your_database_name', 'USER': 'your_db_username', 'PASSWORD': 'your_db_password', 'HOST': '127.0.0.1', 'PORT': '3306', } }
With these changes, your API should correctly accept JSON from Postman and insert it into your MySQL table.
内容的提问来源于stack exchange,提问作者Rounak Modak

