Skip to content

Instantly share code, notes, and snippets.

@powderflask
powderflask / one_to_many.py
Created March 10, 2025 23:08
Django One-to-Many: data models
"""
Many-to-One relations are modelled in django by adding a `ForeignKey` field to the "Many" side model.
But what if the "Many" side model can't be modified? e.g., modelling legacy DB; model is defined by 3rd party app.
Wouldn't it be nice if there were a "OneToManyField", similar to django's `ManyToManyField` that could be added to the "One" side model?
This gist explores a possible data model for this and comes to a surprising conclusion...
"""
# Idea: Use a ManyToManyField and define a OneToOneField on the through-table to enforce One-to-Many. It works!
""" Arjan asked: which do you prefer, TypedDict or dataclass? My response: why choose when you can have both? """
from collections.abc import Mapping
from dataclasses import dataclass
from functools import cached_property
@dataclass
class Options(Mapping):
option1: str = "hello"
@powderflask
powderflask / remove_django_app.py
Created December 19, 2023 04:55
Django management command to wipe all traces of a django app with models from DB
"""
Completely remove all traces of a django app from the DB.
Suggested workflow:
Step 1: carefully remove dependencies on app from code base
Step 2: run this command to remove all traces of app model instances and content types from DB
Step 3: deploy code changes and this command everywhere (e.g., on stage and production codebase and DB)
"""
Patch for https://code.djangoproject.com/ticket/32244
Concept:
- define a ModelPkField intended specifically to define a read-only pk field.
- validates that the pk value in the post data matches the form's instance, (or that the pk value is None if form has no instance)
i.e., verify that no one tampered with the form's pk data on the round trip
- ModelFormSet uses this field type to define these hidden pk fields, and returns the form's original instance if it validates
"""
from django.core.exceptions import ValidationError
from django.forms.fields import Field