Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between get_by_natural_key and natural_key

As I understand, the model manager's get_by_natural_key is used in deserialization and the natural_key is used in serialization. Is this true ? If not what are the differences ?

And also, do we need to give the --natural-foreign and --natural-primary key always ? Are there any way to force serializing/deserializing via natural key ?

like image 388
Mohan Avatar asked Jul 17 '14 17:07

Mohan


1 Answers

As you say, Django uses get_by_natural_key for deserialization and natural_key for serialization.

As stated in the documentation you don't need to define both of them. You can safely use only one of them.

If you need to serialize your model using natural keys inside your code you have to use serializers.serialize() with use_natural_foreign_keys=True and/or use_natural_primary_keys=True.

If you need to serialize/deserialize some objects using natural keys and admin.py dumpdata then you have to pass --natural-foreign and/or --natural-primary if you don't they will be serialized/deserialized with default (non natural) behavior.

To "force" natural keys in dumpdata you can create a shell alias.

If you need more advanced model serialization/deserialization I suggest you to use an external component like Django REST Framework serializers or write your own one.

like image 151
Luca Avatar answered Sep 28 '22 07:09

Luca