1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
|
%global _empty_manifest_terminate_build 0
Name: python-natural-keys
Version: 2.0.0
Release: 1
Summary: Enhanced support for natural keys in Django and Django REST Framework
License: MIT
URL: https://github.com/wq/django-natural-keys
Source0: https://mirrors.aliyun.com/pypi/web/packages/06/b5/d24c797c0eec5e301384eca6ef876aee2c341661877555c76448768e5949/natural-keys-2.0.0.tar.gz
BuildArch: noarch
Requires: python3-html-json-forms
%description
# Django Natural Keys
Enhanced support for [natural keys] in Django and [Django REST Framework]. Extracted from [wq.db] for general use.
*Django Natural Keys* provides a number of useful model methods (e.g. `get_or_create_by_natural_key()`) that speed up working with natural keys in Django. The module also provides a couple of serializer classes that streamline creating REST API support for models with natural keys.
[](https://pypi.org/project/natural-keys/)
[](https://github.com/wq/django-natural-keys/releases)
[](https://github.com/wq/django-natural-keys/blob/main/LICENSE)
[](https://github.com/wq/django-natural-keys/stargazers)
[](https://github.com/wq/django-natural-keys/network)
[](https://github.com/wq/django-natural-keys/issues)
[](https://github.com/wq/django-natural-keys/actions/workflows/test.yml)
[](https://pypi.org/project/natural-keys/)
[](https://pypi.org/project/natural-keys/)
## Usage
*Django Natural Keys* is available via PyPI:
```bash
# Recommended: create virtual environment
# python3 -m venv venv
# . venv/bin/activate
pip install natural-keys
```
### Model API
To use [natural keys] in vanilla Django, you need to define a `natural_key()` method on your Model class and a `get_natural_key()` method on the Manager class. With *Django Natural Keys*, you can instead extend `NaturalKeyModel` and define one of the following:
* A [`UniqueConstraint`][UniqueConstraint] in `Meta.constraints` (recommended),
* A tuple in [`Meta.unique_together`][unique_together], or
* A [model field][unique] (other than `AutoField`) with `unique=True`
The first unique constraint found will be treated as the natural key for the model, and all of the necessary functions for working with natural keys will automatically work.
```python
from natural_keys import NaturalKeyModel
class Event(NaturalKeyModel):
name = models.CharField(max_length=255)
date = models.DateField()
class Meta:
constraints = [
models.UniqueConstraint(
fields=('name', 'date'),
name='event_natural_key',
)
]
class Note(models.Model):
event = models.ForeignKey(Event)
note = models.TextField()
```
or
```python
from natural_keys import NaturalKeyModel
class Event(NaturalKeyModel):
name = models.CharField(unique=True)
```
The following methods will then be available on your Model and its Manager:
```python
# Default Django methods
instance = Event.objects.get_by_natural_key('ABC123', date(2016, 1, 1))
instance.natural_key == ('ABC123', date(2016, 1, 1))
# get_or_create + natural keys
instance, is_new = Event.objects.get_or_create_by_natural_key('ABC123', date(2016, 1, 1))
# Like get_or_create_by_natural_key, but discards is_new
# Useful for quick lookup/creation when you don't care whether the object exists already
instance = Event.objects.find('ABC123', date(2016, 1, 1))
note = Note.objects.create(
event=Event.objects.find('ABC123', date(2016, 1, 1)),
note="This is a note"
)
instance == note.event
# Inspect natural key fields on a model without instantiating it
Event.get_natural_key_fields() == ('name', 'date')
```
#### Nested Natural Keys
One key feature of *Django Natural Keys* is that it will automatically traverse `ForeignKey`s to related models (which should also be `NaturalKeyModel` classes). This makes it possible to define complex, arbitrarily nested natural keys with minimal effort.
```python
class Place(NaturalKeyModel):
name = models.CharField(max_length=255, unique=True)
class Event(NaturalKeyModel):
place = models.ForeignKey(Place)
date = models.DateField()
class Meta:
constraints = [
models.UniqueConstraint(
fields=('place', 'date'),
name='event_natural_key',
)
]
```
```python
Event.get_natural_key_fields() == ('place__name', 'date')
instance = Event.find('ABC123', date(2016, 1, 1))
instance.place.name == 'ABC123'
```
### REST Framework Support
*Django Natural Keys* provides several integrations with [Django REST Framework], primarily through custom Serializer classes. In most cases, you will want to use either:
* `NaturalKeyModelSerializer`, or
* The `natural_key_slug` pseudo-field (see below)
If you have only a single model with a single char field for its natural key, you probably do not need to use either of these integrations. In your view, you can just use Django REST Framework's built in `lookup_field` to point directly to your natural key.
#### `NaturalKeyModelSerializer`
`NaturalKeyModelSerializer` facilitates handling complex natural keys in your rest API. It can be used with a `NaturalKeyModel`, or (more commonly) a model that has a foreign key to a `NaturalKeyModel` but is not a `NaturalKeyModel` itself. (One concrete example of this is the [vera.Report] model, which has a ForeignKey to [vera.Event], which is a `NaturalKeyModel`).
`NaturalKeyModelSerializer` extends DRF's [ModelSerializer], but uses `NaturalKeySerializer` for each foreign key that points to a `NaturalKeyModel`. When `update()` or `create()`ing the primary model, the nested `NaturalKeySerializer`s will automatically create instances of referenced models if they do not exist already (via the `find()` method described above). Note that `NaturalKeyModelSerializer` does not override DRF's default behavior for other fields, whether or not they form part of the primary model's natural key.
`NaturalKeySerializer` can technically be used as a top level serializer, though this is not recommended. `NaturalKeySerializer` is designed for dealing with nested natural keys and does not support updates or non-natural key fields. Even when used together with `NaturalKeyModelSerializer`, `NaturalKeySerializer` never updates an existing related model instance. Instead, it will repoint the foreign key to another (potentially new) instance of the related model. It may help to think of `NaturalKeySerializer` as a special [RelatedField] class rather than as a `Serializer` per se.
You can use `NaturalKeyModelSerializer` with [Django REST Framework] and/or [wq.db] just like any other serializer:
```python
# Django REST Framework usage example
from rest_framework import viewsets
from rest_framework import routers
from natural_keys import NaturalKeyModelSerializer
from .models import Event, Note
class EventSerializer(NaturalKeyModelSerializer):
class Meta:
model = Event
class NoteSerializer(NaturalKeyModelSerializer):
class Meta:
model = Note
class EventViewSet(viewsets.ModelViewSet):
queryset = Event.objects.all()
serializer_class = EventSerializer
class NoteViewSet(viewsets.ModelViewSet):
queryset = Note.objects.all()
serializer_class = NoteSerializer
router = routers.DefaultRouter()
router.register(r'events', EventViewSet)
router.register(r'notes', NoteViewSet)
# wq.db usage example
from wq.db import rest
from natural_keys import NaturalKeyModelSerializer
from .models import Event, Note
rest.router.register_model(Note, serializer=NaturalKeyModelSerializer)
rest.router.register_model(Event, serializer=NaturalKeyModelSerializer)
```
Once this is set up, you can use your REST API to create and view your `NaturalKeyModel` instances and related data. To facilitate integration with regular HTML Forms, *Django Natural Keys* is integrated with the [HTML JSON Forms] package, which supports nested keys via an array naming convention, as the examples below demonstrate.
```html
<form action="/events/" method="post">
<input name="place[name]">
<input type="date" name="date">
</form>
```
```js
// /events.json
[
{
"id": 123,
"place": {"name": "ABC123"},
"date": "2016-01-01"
}
]
```
```html
<form action="/notes/" method="post">
<input name="event[place][name]">
<input type="date" name="event[date]">
<textarea name="note"></textarea>
</form>
```
```js
// /notes.json
[
{
"id": 12345,
"event": {
"place": {"name": "ABC123"},
"date": "2016-01-01"
},
"note": "This is a note"
}
]
```
### Natural Key Slugs
As an alternative to using `NaturalKeyModelSerializer` / `NaturalKeySerializer`, you can also use a single slug-like field for lookup and serialization. `NaturalKeyModel` (and its associated queryset) defines a pseudo-field, `natural_key_slug`, for this purpose.
```python
class Place(NaturalKeyModel):
name = models.CharField(max_length=255, unique=True)
class Room(NaturalKeyModel)
place = models.ForeignKey(Place, models.ON_DELETE)
name = models.CharField(max_length=255)
class Meta:
unique_together = (('place', 'name'),)
```
```python
room = Room.objects.find("ABC123", "MainHall")
assert(room.natural_key_slug == "ABC123-MainHall")
assert(room == Room.objects.get(natural_key_slug="ABC123-MainHall"))
```
You can expose this functionality in your REST API to expose natural keys instead of database-generated ids. To do this, you will likely want to do the following:
1. Create a regular serializer with `id = serializers.ReadOnlyField(source='natural_key_slug')`
2. Set `lookup_field = 'natural_key_slug'` on your `ModelViewSet` (or similar generic class) and update the URL registration accordingly
3. Ensure foreign keys on any related models are serialized with `serializers.SlugRelatedField(slug_field='natural_key_slug')`
In [wq.db], all three of the above can be achieved by setting the `"lookup"` attribute when registering with the [router]:
```python
# myapp/rest.py
from wq.db import rest
from .models import Room
rest.router.register_model(
Room,
fields='__all__',
lookup='natural_key_slug',
)
```
Note that the `natural_key_slug` may not behave as expected if any of the component values contain the delimiter character (`-` by default). To mitigate this, you can set `natural_key_separator` on the model class to another character.
[natural keys]: https://docs.djangoproject.com/en/3.2/topics/serialization/#natural-keys
[UniqueConstraint]: https://docs.djangoproject.com/en/3.2/ref/models/constraints/#uniqueconstraint
[unique_together]: https://docs.djangoproject.com/en/3.2/ref/models/options/#unique-together
[unique]: https://docs.djangoproject.com/en/3.2/ref/models/fields/#unique
[wq.db]: https://wq.io/wq.db/
[Django REST Framework]: http://www.django-rest-framework.org/
[vera.Report]:https://github.com/powered-by-wq/vera#report
[vera.Event]: https://github.com/powered-by-wq/vera#event
[ModelSerializer]: https://www.django-rest-framework.org/api-guide/serializers/#modelserializer
[RelatedField]: https://www.django-rest-framework.org/api-guide/relations/
[HTML JSON Forms]: https://github.com/wq/html-json-forms
[router]: https://wq.io/wq.db/router
%package -n python3-natural-keys
Summary: Enhanced support for natural keys in Django and Django REST Framework
Provides: python-natural-keys
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-natural-keys
# Django Natural Keys
Enhanced support for [natural keys] in Django and [Django REST Framework]. Extracted from [wq.db] for general use.
*Django Natural Keys* provides a number of useful model methods (e.g. `get_or_create_by_natural_key()`) that speed up working with natural keys in Django. The module also provides a couple of serializer classes that streamline creating REST API support for models with natural keys.
[](https://pypi.org/project/natural-keys/)
[](https://github.com/wq/django-natural-keys/releases)
[](https://github.com/wq/django-natural-keys/blob/main/LICENSE)
[](https://github.com/wq/django-natural-keys/stargazers)
[](https://github.com/wq/django-natural-keys/network)
[](https://github.com/wq/django-natural-keys/issues)
[](https://github.com/wq/django-natural-keys/actions/workflows/test.yml)
[](https://pypi.org/project/natural-keys/)
[](https://pypi.org/project/natural-keys/)
## Usage
*Django Natural Keys* is available via PyPI:
```bash
# Recommended: create virtual environment
# python3 -m venv venv
# . venv/bin/activate
pip install natural-keys
```
### Model API
To use [natural keys] in vanilla Django, you need to define a `natural_key()` method on your Model class and a `get_natural_key()` method on the Manager class. With *Django Natural Keys*, you can instead extend `NaturalKeyModel` and define one of the following:
* A [`UniqueConstraint`][UniqueConstraint] in `Meta.constraints` (recommended),
* A tuple in [`Meta.unique_together`][unique_together], or
* A [model field][unique] (other than `AutoField`) with `unique=True`
The first unique constraint found will be treated as the natural key for the model, and all of the necessary functions for working with natural keys will automatically work.
```python
from natural_keys import NaturalKeyModel
class Event(NaturalKeyModel):
name = models.CharField(max_length=255)
date = models.DateField()
class Meta:
constraints = [
models.UniqueConstraint(
fields=('name', 'date'),
name='event_natural_key',
)
]
class Note(models.Model):
event = models.ForeignKey(Event)
note = models.TextField()
```
or
```python
from natural_keys import NaturalKeyModel
class Event(NaturalKeyModel):
name = models.CharField(unique=True)
```
The following methods will then be available on your Model and its Manager:
```python
# Default Django methods
instance = Event.objects.get_by_natural_key('ABC123', date(2016, 1, 1))
instance.natural_key == ('ABC123', date(2016, 1, 1))
# get_or_create + natural keys
instance, is_new = Event.objects.get_or_create_by_natural_key('ABC123', date(2016, 1, 1))
# Like get_or_create_by_natural_key, but discards is_new
# Useful for quick lookup/creation when you don't care whether the object exists already
instance = Event.objects.find('ABC123', date(2016, 1, 1))
note = Note.objects.create(
event=Event.objects.find('ABC123', date(2016, 1, 1)),
note="This is a note"
)
instance == note.event
# Inspect natural key fields on a model without instantiating it
Event.get_natural_key_fields() == ('name', 'date')
```
#### Nested Natural Keys
One key feature of *Django Natural Keys* is that it will automatically traverse `ForeignKey`s to related models (which should also be `NaturalKeyModel` classes). This makes it possible to define complex, arbitrarily nested natural keys with minimal effort.
```python
class Place(NaturalKeyModel):
name = models.CharField(max_length=255, unique=True)
class Event(NaturalKeyModel):
place = models.ForeignKey(Place)
date = models.DateField()
class Meta:
constraints = [
models.UniqueConstraint(
fields=('place', 'date'),
name='event_natural_key',
)
]
```
```python
Event.get_natural_key_fields() == ('place__name', 'date')
instance = Event.find('ABC123', date(2016, 1, 1))
instance.place.name == 'ABC123'
```
### REST Framework Support
*Django Natural Keys* provides several integrations with [Django REST Framework], primarily through custom Serializer classes. In most cases, you will want to use either:
* `NaturalKeyModelSerializer`, or
* The `natural_key_slug` pseudo-field (see below)
If you have only a single model with a single char field for its natural key, you probably do not need to use either of these integrations. In your view, you can just use Django REST Framework's built in `lookup_field` to point directly to your natural key.
#### `NaturalKeyModelSerializer`
`NaturalKeyModelSerializer` facilitates handling complex natural keys in your rest API. It can be used with a `NaturalKeyModel`, or (more commonly) a model that has a foreign key to a `NaturalKeyModel` but is not a `NaturalKeyModel` itself. (One concrete example of this is the [vera.Report] model, which has a ForeignKey to [vera.Event], which is a `NaturalKeyModel`).
`NaturalKeyModelSerializer` extends DRF's [ModelSerializer], but uses `NaturalKeySerializer` for each foreign key that points to a `NaturalKeyModel`. When `update()` or `create()`ing the primary model, the nested `NaturalKeySerializer`s will automatically create instances of referenced models if they do not exist already (via the `find()` method described above). Note that `NaturalKeyModelSerializer` does not override DRF's default behavior for other fields, whether or not they form part of the primary model's natural key.
`NaturalKeySerializer` can technically be used as a top level serializer, though this is not recommended. `NaturalKeySerializer` is designed for dealing with nested natural keys and does not support updates or non-natural key fields. Even when used together with `NaturalKeyModelSerializer`, `NaturalKeySerializer` never updates an existing related model instance. Instead, it will repoint the foreign key to another (potentially new) instance of the related model. It may help to think of `NaturalKeySerializer` as a special [RelatedField] class rather than as a `Serializer` per se.
You can use `NaturalKeyModelSerializer` with [Django REST Framework] and/or [wq.db] just like any other serializer:
```python
# Django REST Framework usage example
from rest_framework import viewsets
from rest_framework import routers
from natural_keys import NaturalKeyModelSerializer
from .models import Event, Note
class EventSerializer(NaturalKeyModelSerializer):
class Meta:
model = Event
class NoteSerializer(NaturalKeyModelSerializer):
class Meta:
model = Note
class EventViewSet(viewsets.ModelViewSet):
queryset = Event.objects.all()
serializer_class = EventSerializer
class NoteViewSet(viewsets.ModelViewSet):
queryset = Note.objects.all()
serializer_class = NoteSerializer
router = routers.DefaultRouter()
router.register(r'events', EventViewSet)
router.register(r'notes', NoteViewSet)
# wq.db usage example
from wq.db import rest
from natural_keys import NaturalKeyModelSerializer
from .models import Event, Note
rest.router.register_model(Note, serializer=NaturalKeyModelSerializer)
rest.router.register_model(Event, serializer=NaturalKeyModelSerializer)
```
Once this is set up, you can use your REST API to create and view your `NaturalKeyModel` instances and related data. To facilitate integration with regular HTML Forms, *Django Natural Keys* is integrated with the [HTML JSON Forms] package, which supports nested keys via an array naming convention, as the examples below demonstrate.
```html
<form action="/events/" method="post">
<input name="place[name]">
<input type="date" name="date">
</form>
```
```js
// /events.json
[
{
"id": 123,
"place": {"name": "ABC123"},
"date": "2016-01-01"
}
]
```
```html
<form action="/notes/" method="post">
<input name="event[place][name]">
<input type="date" name="event[date]">
<textarea name="note"></textarea>
</form>
```
```js
// /notes.json
[
{
"id": 12345,
"event": {
"place": {"name": "ABC123"},
"date": "2016-01-01"
},
"note": "This is a note"
}
]
```
### Natural Key Slugs
As an alternative to using `NaturalKeyModelSerializer` / `NaturalKeySerializer`, you can also use a single slug-like field for lookup and serialization. `NaturalKeyModel` (and its associated queryset) defines a pseudo-field, `natural_key_slug`, for this purpose.
```python
class Place(NaturalKeyModel):
name = models.CharField(max_length=255, unique=True)
class Room(NaturalKeyModel)
place = models.ForeignKey(Place, models.ON_DELETE)
name = models.CharField(max_length=255)
class Meta:
unique_together = (('place', 'name'),)
```
```python
room = Room.objects.find("ABC123", "MainHall")
assert(room.natural_key_slug == "ABC123-MainHall")
assert(room == Room.objects.get(natural_key_slug="ABC123-MainHall"))
```
You can expose this functionality in your REST API to expose natural keys instead of database-generated ids. To do this, you will likely want to do the following:
1. Create a regular serializer with `id = serializers.ReadOnlyField(source='natural_key_slug')`
2. Set `lookup_field = 'natural_key_slug'` on your `ModelViewSet` (or similar generic class) and update the URL registration accordingly
3. Ensure foreign keys on any related models are serialized with `serializers.SlugRelatedField(slug_field='natural_key_slug')`
In [wq.db], all three of the above can be achieved by setting the `"lookup"` attribute when registering with the [router]:
```python
# myapp/rest.py
from wq.db import rest
from .models import Room
rest.router.register_model(
Room,
fields='__all__',
lookup='natural_key_slug',
)
```
Note that the `natural_key_slug` may not behave as expected if any of the component values contain the delimiter character (`-` by default). To mitigate this, you can set `natural_key_separator` on the model class to another character.
[natural keys]: https://docs.djangoproject.com/en/3.2/topics/serialization/#natural-keys
[UniqueConstraint]: https://docs.djangoproject.com/en/3.2/ref/models/constraints/#uniqueconstraint
[unique_together]: https://docs.djangoproject.com/en/3.2/ref/models/options/#unique-together
[unique]: https://docs.djangoproject.com/en/3.2/ref/models/fields/#unique
[wq.db]: https://wq.io/wq.db/
[Django REST Framework]: http://www.django-rest-framework.org/
[vera.Report]:https://github.com/powered-by-wq/vera#report
[vera.Event]: https://github.com/powered-by-wq/vera#event
[ModelSerializer]: https://www.django-rest-framework.org/api-guide/serializers/#modelserializer
[RelatedField]: https://www.django-rest-framework.org/api-guide/relations/
[HTML JSON Forms]: https://github.com/wq/html-json-forms
[router]: https://wq.io/wq.db/router
%package help
Summary: Development documents and examples for natural-keys
Provides: python3-natural-keys-doc
%description help
# Django Natural Keys
Enhanced support for [natural keys] in Django and [Django REST Framework]. Extracted from [wq.db] for general use.
*Django Natural Keys* provides a number of useful model methods (e.g. `get_or_create_by_natural_key()`) that speed up working with natural keys in Django. The module also provides a couple of serializer classes that streamline creating REST API support for models with natural keys.
[](https://pypi.org/project/natural-keys/)
[](https://github.com/wq/django-natural-keys/releases)
[](https://github.com/wq/django-natural-keys/blob/main/LICENSE)
[](https://github.com/wq/django-natural-keys/stargazers)
[](https://github.com/wq/django-natural-keys/network)
[](https://github.com/wq/django-natural-keys/issues)
[](https://github.com/wq/django-natural-keys/actions/workflows/test.yml)
[](https://pypi.org/project/natural-keys/)
[](https://pypi.org/project/natural-keys/)
## Usage
*Django Natural Keys* is available via PyPI:
```bash
# Recommended: create virtual environment
# python3 -m venv venv
# . venv/bin/activate
pip install natural-keys
```
### Model API
To use [natural keys] in vanilla Django, you need to define a `natural_key()` method on your Model class and a `get_natural_key()` method on the Manager class. With *Django Natural Keys*, you can instead extend `NaturalKeyModel` and define one of the following:
* A [`UniqueConstraint`][UniqueConstraint] in `Meta.constraints` (recommended),
* A tuple in [`Meta.unique_together`][unique_together], or
* A [model field][unique] (other than `AutoField`) with `unique=True`
The first unique constraint found will be treated as the natural key for the model, and all of the necessary functions for working with natural keys will automatically work.
```python
from natural_keys import NaturalKeyModel
class Event(NaturalKeyModel):
name = models.CharField(max_length=255)
date = models.DateField()
class Meta:
constraints = [
models.UniqueConstraint(
fields=('name', 'date'),
name='event_natural_key',
)
]
class Note(models.Model):
event = models.ForeignKey(Event)
note = models.TextField()
```
or
```python
from natural_keys import NaturalKeyModel
class Event(NaturalKeyModel):
name = models.CharField(unique=True)
```
The following methods will then be available on your Model and its Manager:
```python
# Default Django methods
instance = Event.objects.get_by_natural_key('ABC123', date(2016, 1, 1))
instance.natural_key == ('ABC123', date(2016, 1, 1))
# get_or_create + natural keys
instance, is_new = Event.objects.get_or_create_by_natural_key('ABC123', date(2016, 1, 1))
# Like get_or_create_by_natural_key, but discards is_new
# Useful for quick lookup/creation when you don't care whether the object exists already
instance = Event.objects.find('ABC123', date(2016, 1, 1))
note = Note.objects.create(
event=Event.objects.find('ABC123', date(2016, 1, 1)),
note="This is a note"
)
instance == note.event
# Inspect natural key fields on a model without instantiating it
Event.get_natural_key_fields() == ('name', 'date')
```
#### Nested Natural Keys
One key feature of *Django Natural Keys* is that it will automatically traverse `ForeignKey`s to related models (which should also be `NaturalKeyModel` classes). This makes it possible to define complex, arbitrarily nested natural keys with minimal effort.
```python
class Place(NaturalKeyModel):
name = models.CharField(max_length=255, unique=True)
class Event(NaturalKeyModel):
place = models.ForeignKey(Place)
date = models.DateField()
class Meta:
constraints = [
models.UniqueConstraint(
fields=('place', 'date'),
name='event_natural_key',
)
]
```
```python
Event.get_natural_key_fields() == ('place__name', 'date')
instance = Event.find('ABC123', date(2016, 1, 1))
instance.place.name == 'ABC123'
```
### REST Framework Support
*Django Natural Keys* provides several integrations with [Django REST Framework], primarily through custom Serializer classes. In most cases, you will want to use either:
* `NaturalKeyModelSerializer`, or
* The `natural_key_slug` pseudo-field (see below)
If you have only a single model with a single char field for its natural key, you probably do not need to use either of these integrations. In your view, you can just use Django REST Framework's built in `lookup_field` to point directly to your natural key.
#### `NaturalKeyModelSerializer`
`NaturalKeyModelSerializer` facilitates handling complex natural keys in your rest API. It can be used with a `NaturalKeyModel`, or (more commonly) a model that has a foreign key to a `NaturalKeyModel` but is not a `NaturalKeyModel` itself. (One concrete example of this is the [vera.Report] model, which has a ForeignKey to [vera.Event], which is a `NaturalKeyModel`).
`NaturalKeyModelSerializer` extends DRF's [ModelSerializer], but uses `NaturalKeySerializer` for each foreign key that points to a `NaturalKeyModel`. When `update()` or `create()`ing the primary model, the nested `NaturalKeySerializer`s will automatically create instances of referenced models if they do not exist already (via the `find()` method described above). Note that `NaturalKeyModelSerializer` does not override DRF's default behavior for other fields, whether or not they form part of the primary model's natural key.
`NaturalKeySerializer` can technically be used as a top level serializer, though this is not recommended. `NaturalKeySerializer` is designed for dealing with nested natural keys and does not support updates or non-natural key fields. Even when used together with `NaturalKeyModelSerializer`, `NaturalKeySerializer` never updates an existing related model instance. Instead, it will repoint the foreign key to another (potentially new) instance of the related model. It may help to think of `NaturalKeySerializer` as a special [RelatedField] class rather than as a `Serializer` per se.
You can use `NaturalKeyModelSerializer` with [Django REST Framework] and/or [wq.db] just like any other serializer:
```python
# Django REST Framework usage example
from rest_framework import viewsets
from rest_framework import routers
from natural_keys import NaturalKeyModelSerializer
from .models import Event, Note
class EventSerializer(NaturalKeyModelSerializer):
class Meta:
model = Event
class NoteSerializer(NaturalKeyModelSerializer):
class Meta:
model = Note
class EventViewSet(viewsets.ModelViewSet):
queryset = Event.objects.all()
serializer_class = EventSerializer
class NoteViewSet(viewsets.ModelViewSet):
queryset = Note.objects.all()
serializer_class = NoteSerializer
router = routers.DefaultRouter()
router.register(r'events', EventViewSet)
router.register(r'notes', NoteViewSet)
# wq.db usage example
from wq.db import rest
from natural_keys import NaturalKeyModelSerializer
from .models import Event, Note
rest.router.register_model(Note, serializer=NaturalKeyModelSerializer)
rest.router.register_model(Event, serializer=NaturalKeyModelSerializer)
```
Once this is set up, you can use your REST API to create and view your `NaturalKeyModel` instances and related data. To facilitate integration with regular HTML Forms, *Django Natural Keys* is integrated with the [HTML JSON Forms] package, which supports nested keys via an array naming convention, as the examples below demonstrate.
```html
<form action="/events/" method="post">
<input name="place[name]">
<input type="date" name="date">
</form>
```
```js
// /events.json
[
{
"id": 123,
"place": {"name": "ABC123"},
"date": "2016-01-01"
}
]
```
```html
<form action="/notes/" method="post">
<input name="event[place][name]">
<input type="date" name="event[date]">
<textarea name="note"></textarea>
</form>
```
```js
// /notes.json
[
{
"id": 12345,
"event": {
"place": {"name": "ABC123"},
"date": "2016-01-01"
},
"note": "This is a note"
}
]
```
### Natural Key Slugs
As an alternative to using `NaturalKeyModelSerializer` / `NaturalKeySerializer`, you can also use a single slug-like field for lookup and serialization. `NaturalKeyModel` (and its associated queryset) defines a pseudo-field, `natural_key_slug`, for this purpose.
```python
class Place(NaturalKeyModel):
name = models.CharField(max_length=255, unique=True)
class Room(NaturalKeyModel)
place = models.ForeignKey(Place, models.ON_DELETE)
name = models.CharField(max_length=255)
class Meta:
unique_together = (('place', 'name'),)
```
```python
room = Room.objects.find("ABC123", "MainHall")
assert(room.natural_key_slug == "ABC123-MainHall")
assert(room == Room.objects.get(natural_key_slug="ABC123-MainHall"))
```
You can expose this functionality in your REST API to expose natural keys instead of database-generated ids. To do this, you will likely want to do the following:
1. Create a regular serializer with `id = serializers.ReadOnlyField(source='natural_key_slug')`
2. Set `lookup_field = 'natural_key_slug'` on your `ModelViewSet` (or similar generic class) and update the URL registration accordingly
3. Ensure foreign keys on any related models are serialized with `serializers.SlugRelatedField(slug_field='natural_key_slug')`
In [wq.db], all three of the above can be achieved by setting the `"lookup"` attribute when registering with the [router]:
```python
# myapp/rest.py
from wq.db import rest
from .models import Room
rest.router.register_model(
Room,
fields='__all__',
lookup='natural_key_slug',
)
```
Note that the `natural_key_slug` may not behave as expected if any of the component values contain the delimiter character (`-` by default). To mitigate this, you can set `natural_key_separator` on the model class to another character.
[natural keys]: https://docs.djangoproject.com/en/3.2/topics/serialization/#natural-keys
[UniqueConstraint]: https://docs.djangoproject.com/en/3.2/ref/models/constraints/#uniqueconstraint
[unique_together]: https://docs.djangoproject.com/en/3.2/ref/models/options/#unique-together
[unique]: https://docs.djangoproject.com/en/3.2/ref/models/fields/#unique
[wq.db]: https://wq.io/wq.db/
[Django REST Framework]: http://www.django-rest-framework.org/
[vera.Report]:https://github.com/powered-by-wq/vera#report
[vera.Event]: https://github.com/powered-by-wq/vera#event
[ModelSerializer]: https://www.django-rest-framework.org/api-guide/serializers/#modelserializer
[RelatedField]: https://www.django-rest-framework.org/api-guide/relations/
[HTML JSON Forms]: https://github.com/wq/html-json-forms
[router]: https://wq.io/wq.db/router
%prep
%autosetup -n natural-keys-2.0.0
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "\"/%h/%f.gz\"\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-natural-keys -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Thu Jun 08 2023 Python_Bot <Python_Bot@openeuler.org> - 2.0.0-1
- Package Spec generated
|