0
# Core Models and Managers
1
2
Database models for storing preferences and manager classes for cached preference access with automatic synchronization. These components form the foundation of the dynamic preferences system.
3
4
## Capabilities
5
6
### Base Preference Model
7
8
Abstract Django model that provides common functionality for all preference models, including value serialization and preference metadata access.
9
10
```python { .api }
11
class BasePreferenceModel(models.Model):
12
"""
13
Abstract base model for all preference models.
14
15
Fields:
16
- section (CharField): The section under which the preference is declared
17
- name (CharField): A name for the preference
18
- raw_value (TextField): Serialized value (should not be accessed directly)
19
"""
20
section = models.CharField(max_length=150)
21
name = models.CharField(max_length=150)
22
raw_value = models.TextField()
23
24
@property
25
def preference(self):
26
"""Returns the preference object from registry."""
27
28
@property
29
def verbose_name(self) -> str:
30
"""Returns preference verbose name."""
31
32
@property
33
def help_text(self) -> str:
34
"""Returns preference help text."""
35
36
@property
37
def value(self):
38
"""Gets/sets deserialized preference value."""
39
40
@value.setter
41
def value(self, value):
42
"""Sets the preference value with automatic serialization."""
43
44
def set_value(self, value):
45
"""Save serialized value to raw_value field."""
46
47
def get_value(self):
48
"""Return deserialized raw_value."""
49
50
def save(self, **kwargs):
51
"""Override to set default value if needed."""
52
```
53
54
### Global Preference Model
55
56
Concrete Django model for storing global (site-wide) preferences.
57
58
```python { .api }
59
class GlobalPreferenceModel(BasePreferenceModel):
60
"""
61
Model for global preferences (site-wide settings).
62
63
Meta:
64
- unique_together = ("section", "name")
65
"""
66
class Meta:
67
unique_together = ("section", "name")
68
```
69
70
### Per Instance Preference Model
71
72
Abstract Django model for preferences tied to specific model instances (e.g., user-specific preferences).
73
74
```python { .api }
75
class PerInstancePreferenceModel(BasePreferenceModel):
76
"""
77
Abstract base for preferences tied to specific model instances.
78
79
Fields:
80
- instance (ForeignKey): The instance concerned by the preference (must be defined in subclass)
81
"""
82
83
@classmethod
84
def get_instance_model(cls):
85
"""Returns the model class for the instance field."""
86
```
87
88
### Preferences Manager
89
90
Manager class that handles preference retrieval, caching, and database synchronization. Implements Mapping interface for dict-like access.
91
92
```python { .api }
93
class PreferencesManager:
94
"""
95
Handle retrieving/caching of preferences.
96
97
Args:
98
- model: The preference model class
99
- registry: The preference registry
100
- **kwargs: Additional options (instance, etc.)
101
"""
102
103
def __init__(self, model, registry, **kwargs):
104
"""Initialize with model and registry."""
105
106
def __getitem__(self, key: str):
107
"""Get preference value by key (section__name format)."""
108
109
def __setitem__(self, key: str, value):
110
"""Set preference value by key."""
111
112
def get(self, key: str, no_cache: bool = False):
113
"""
114
Return preference value with optional cache bypass.
115
116
Args:
117
- key: Preference identifier (section__name)
118
- no_cache: If True, bypass cache and load from database
119
120
Returns:
121
Preference value
122
"""
123
124
def all(self) -> dict:
125
"""Return dictionary of all preferences organized by section."""
126
127
def by_name(self) -> dict:
128
"""Return dict with preferences without section in identifier."""
129
130
def get_by_name(self, name: str):
131
"""Get preference by name only (without section)."""
132
133
def update_db_pref(self, section: str, name: str, value):
134
"""Update preference in database."""
135
136
def create_db_pref(self, section: str, name: str, value):
137
"""Create new preference in database."""
138
139
def load_from_db(self, cache: bool = False):
140
"""Load preferences directly from database."""
141
142
@property
143
def queryset(self):
144
"""Model queryset (filtered by instance if applicable)."""
145
146
@property
147
def cache(self):
148
"""Django cache backend."""
149
```
150
151
## Usage Examples
152
153
### Basic Preference Access
154
155
```python
156
from dynamic_preferences.registries import global_preferences_registry
157
158
# Get manager instance
159
global_preferences = global_preferences_registry.manager()
160
161
# Get preference value
162
site_title = global_preferences['general__title']
163
164
# Set preference value
165
global_preferences['general__maintenance_mode'] = True
166
167
# Get all preferences
168
all_prefs = global_preferences.all()
169
# Returns: {'general': {'title': 'My Site', 'maintenance_mode': True}, ...}
170
```
171
172
### Cache Management
173
174
```python
175
# Bypass cache for fresh database value
176
fresh_value = global_preferences.get('general__title', no_cache=True)
177
178
# Reload all preferences from database
179
global_preferences.load_from_db()
180
```
181
182
### Working with Sections
183
184
```python
185
# Get preferences organized by section
186
preferences_by_section = global_preferences.all()
187
188
# Get preferences without section prefixes
189
preferences_by_name = global_preferences.by_name()
190
# Returns: {'title': 'My Site', 'maintenance_mode': True, ...}
191
192
# Get preference by name only (if unique)
193
title = global_preferences.get_by_name('title')
194
```