You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Postman或Rest API在Django中向MySQL插入JSON数据?

Fixing Django REST API JSON Insert Issues with MySQL

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 is request.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 into tbl_user via 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

  1. Map your model to the correct database table:
    If your fetchdata model should point to tbl_user, add a Meta class 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 table
    
  2. Align serializer fields with your JSON payload:
    Make sure your serializer matches the keys you’re sending from Postman. If you’re sending name, email, pwd but your model uses user_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']
    
  3. Postman request setup:

    • Send a POST request 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"
      }
      
  4. Verify MySQL database configuration:
    Double-check your settings.py to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:30:41