简体   繁体   中英

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM