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

基于React Native与Django REST API:Open API数据存入Django关联表问询

Got it, let's break this down step by step—you've got your JSON from the Open API, now you need to get that data into your Django relational models. Here's how to approach this, covering both backend Django setup and frontend data handling:

1. First: Ensure Your Django Models & Relationships Are Correct

Before you start saving data, double-check that your models reflect the relational structure you need. For example, if you're working with books and their authors (a one-to-many relationship), your models might look like this:

# models.py
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)

class Book(models.Model):
    title = models.CharField(max_length=200)
    publication_date = models.DateField()
    # ForeignKey establishes the one-to-many relationship with Author
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')
2. Build Serializers to Handle Relational Data

Django REST Framework (DRF) serializers are how you convert JSON into model instances (and vice versa). For relational data, you'll need to handle nested objects (like author data inside a book entry).

Here's a serializer setup that lets you create both authors and books in one go (using get_or_create to avoid duplicate authors):

# serializers.py
from rest_framework import serializers
from .models import Author, Book

class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ['id', 'name', 'email']

class BookSerializer(serializers.ModelSerializer):
    # Nested serializer to handle author data
    author = AuthorSerializer()

    class Meta:
        model = Book
        fields = ['id', 'title', 'publication_date', 'author']

    def create(self, validated_data):
        # Extract author data from the validated payload
        author_data = validated_data.pop('author')
        # Get existing author or create a new one to avoid duplicates
        author, _ = Author.objects.get_or_create(**author_data)
        # Create the book and link it to the author
        book = Book.objects.create(author=author, **validated_data)
        return book
3. Create a Django API Endpoint to Receive Data

Next, build a view (or viewset) to accept the formatted JSON from your React Native app and save it to the database. For bulk data (common when importing from an Open API), use a bulk create view:

# views.py
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import BookSerializer

class BulkBookCreateView(APIView):
    def post(self, request):
        # Handle both single entries and bulk arrays
        is_bulk = isinstance(request.data, list)
        serializer = BookSerializer(data=request.data, many=is_bulk)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        # Return validation errors if something's wrong
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Don't forget to map this view to a URL in your urls.py:

# urls.py
from django.urls import path
from .views import BulkBookCreateView

urlpatterns = [
    path('api/books/bulk-save/', BulkBookCreateView.as_view(), name='bulk-book-save'),
]
4. Format & Send Data from React Native

Once your Django endpoint is ready, update your React Native code to transform the Open API JSON into a format that matches your serializer, then send it to Django:

// React Native function to fetch and save data
const importOpenApiData = async () => {
  try {
    // Step 1: Fetch data from the Open API
    const openApiRes = await fetch('https://your-open-api-url.com/data');
    const openApiJson = await openApiRes.json();

    // Step 2: Transform data to match Django serializer structure
    const formattedData = openApiJson.map(item => ({
      title: item.book_title, // Map Open API field to Django model field
      publication_date: item.publish_date,
      author: {
        name: item.author_full_name,
        email: item.author_email
      }
    }));

    // Step 3: Send to Django API (add auth token if your API requires it)
    const djangoRes = await fetch('http://your-django-api-url.com/api/books/bulk-save/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR_JWT_TOKEN' // Omit if no auth
      },
      body: JSON.stringify(formattedData)
    });

    if (djangoRes.ok) {
      console.log('Data saved successfully!');
    } else {
      const errorDetails = await djangoRes.json();
      console.error('Save failed:', errorDetails);
    }
  } catch (err) {
    console.error('Request error:', err);
  }
};
Key Tips to Avoid Headaches
  • Deduplicate Relational Objects: Always use get_or_create for related models (like authors) to prevent duplicate entries in your database.
  • Validate Data: DRF serializers handle validation automatically, but make sure your Open API data matches Django's field requirements (e.g., correct date formats, non-null fields).
  • Batch Large Datasets: If you're importing hundreds/thousands of records, use bulk operations (the many=True flag in serializers) to avoid performance issues.
  • Handle Errors: Add proper error handling on both ends—log validation errors in Django and display user-friendly messages in React Native.

内容的提问来源于stack exchange,提问作者Jiwon Kim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:55:17