This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" 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" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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 |