Difference between get_by_natural_key and natural_key
Asked Answered
F

1

7

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 ?

Flannel answered 17/7, 2014 at 17:33 Comment(0)
G
5

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.

Gongorism answered 25/8, 2014 at 19:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.