Add personal-finance transactions API
Python · Django · intermediate · modification
Adds a personal-finance transactions API so the frontend can list, view, and edit a user's transactions. The ViewSet filters the queryset to the authenticated user, the serializer handles validation, and the router wires everything under `/api/transactions/`. Tested locally — listing returns only the caller's transactions, and editing saves changes correctly.
Multi-tenant personal finance app. The API is exposed to authenticated users from the public internet. Each user has their own transactions; reading or modifying another user's data is a security violation. `rest_framework` and the new `transactions` app (its package and `apps.py` were scaffolded with `startapp`) are already in `INSTALLED_APPS`.
Requirements
- Add a `transactions` app with model `Transaction` (fields: `user` FK to the auth User model, `description` CharField max 255, `amount` DecimalField max_digits=10 decimal_places=2, `date` DateField, `created_at` DateTimeField auto_now_add).
- Provide a DRF viewset with `list`, `retrieve`, and `update` (partial) actions at `/api/transactions/`. All endpoints require authentication (`IsAuthenticated`).
- A user must only see their own transactions — never another user's — on every endpoint: `list`, `retrieve`, and `update`. Cross-user access is a data leak.
- The model's default ordering is by `-date` then `-created_at`.
Files touched
- transactions/models.py
- transactions/serializers.py
- transactions/views.py
- transactions/urls.py
- transactions/migrations/__init__.py
- transactions/migrations/0001_initial.py
- config/urls.py
--- transactions/models.py
+from django.conf import settings
+from django.db import models
+
+
+class Transaction(models.Model):
+ user = models.ForeignKey(
+ settings.AUTH_USER_MODEL,
+ on_delete=models.CASCADE,
+ related_name='transactions',
+ )
+ description = models.CharField(max_length=255)
+ amount = models.DecimalField(max_digits=10, decimal_places=2)
+ date = models.DateField()
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ ordering = ['-date', '-created_at']
+
+ def __str__(self):
+ return f'{self.description} ({self.amount})'
+
--- transactions/serializers.py
+from rest_framework import serializers
+
+from .models import Transaction
+
+
+class TransactionSerializer(serializers.ModelSerializer):
+ class Meta: