Django Diagnosis Data Not Appearing in Admin After Endpoint Execution

I am working on a Django project where I process mock patient data and save it to a DiagnosisResult model in the database (SQLite). The goal is for this data to appear in the Django admin interface, but after calling the endpoint, the data doesn't appear in the database or admin.

By "mock," I mean fictional data (not testing framework mocks), which I pre-generated to avoid using real patient data.

Hers is my Minimal Reproducible Example (In order: models.py, views.py, urls.py, sample JSON data, Dockerfile, docker-compose.yml):

models.py

from django.db import models

class Subtype(models.Model):
    CATEGORY_CHOICES = [('Acute', 'Acute'), ('Chronic', 'Chronic')]
    category = models.CharField(max_length=20, choices=CATEGORY_CHOICES)
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name


class DiagnosisResult(models.Model):
    patient_name = models.CharField(max_length=100)
    age = models.IntegerField()
    symptoms = models.TextField()  # Comma-separated list of symptoms
    test_results = models.TextField()
    likely_diagnoses = models.ManyToManyField(Subtype)

    def __str__(self):
        return f"{self.patient_name} (Age: {self.age})"

views.py

import json
from pathlib import Path
from django.http import JsonResponse
from .models import Subtype, DiagnosisResult

# File paths
IS_DOCKER = Path("/app").exists()  # Check if running inside Docker
MOCK_DATA_FILE = (
    Path("/app/apps/diagnosis/mock_data/mock_diagnosis_inputs.json")
    if IS_DOCKER
    else Path(__file__).resolve().parent / "mock_data" / "mock_diagnosis_inputs.json"
)

def process_and_save_mock_diagnoses(request):
    with open(MOCK_DATA_FILE, "r") as file:
        mock_data = json.load(file)

    results = []
    for patient in mock_data:
        likely_subtypes = Subtype.objects.filter(category="Acute")
        diagnosis_result = DiagnosisResult.objects.create(
            patient_name=patient["patient_name"],
            age=patient["age"],
            symptoms=", ".join(patient["symptoms"]),
            test_results=patient["test_results"]
        )
        diagnosis_result.likely_diagnoses.set(likely_subtypes)
        results.append({
            "patient_name": diagnosis_result.patient_name,
            "likely_diagnoses": [subtype.name for subtype in likely_subtypes],
        })

    return JsonResponse(results, safe=False)

urls.py

from django.urls import path
from .views import process_and_save_mock_diagnoses

urlpatterns = [
    path('process-mock-diagnoses/', process_and_save_mock_diagnoses, name='process-mock-diagnoses'),
]

Sample JSON data (mock_diagnosis_inputs.json)

[
    {
        "patient_name": "John Doe",
        "age": 45,
        "symptoms": ["Fatigue", "Fever"],
        "test_results": "High WBC count"
    },
    {
        "patient_name": "Jane Smith",
        "age": 60,
        "symptoms": ["Bruising", "Swollen spleen"],
        "test_results": "Low RBC count"
    }
]

Dockerfile

# Use an official Python image
FROM python:3.12-slim

# Install required system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    python3-venv gcc libpq-dev && \
    apt-get clean && rm -rf /var/lib/apt/lists/*

# Set the working directory in the container
WORKDIR /app

# Copy the backend directory
COPY backend /app

# Install dependencies
RUN python3 -m venv /app/venv && \
    /app/venv/bin/pip install --no-cache-dir -r requirements.txt

# Expose the port for the Django development server
EXPOSE 8000

# Set the default path to include the virtual environment's binaries
ENV PATH="/app/venv/bin:$PATH"

# Command to run the Django server
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

docker-compose.yml

version: '3.8'

services:
  django:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "8000:8000"
    volumes:
      - ./backend:/app
    environment:
      - PYTHONUNBUFFERED=1
Вернуться на верх