简体   繁体   English

get_by_natural_key 和 natural_key 的区别

[英]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.据我了解,模型管理器的 get_by_natural_key 用于反序列化,而 natural_key 用于序列化。 Is this true ?这是真的 ? If not what are the differences ?如果不是,有什么区别?

And also, do we need to give the --natural-foreign and --natural-primary key always ?而且,我们是否需要始终提供 --natural-foreign 和 --natural-primary 键? 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.正如你所说,Django使用get_by_natural_key反序列化和natural_key进行序列化。

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 .如果您需要在代码中使用自然键序列化模型,则必须使用serializers.serialize()use_natural_foreign_keys=True和/或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.如果您需要使用自然键和admin.py dumpdata序列化/反序列化某些对象,那么您必须传递--natural-foreign和/或--natural-primary如果不这样做,它们将被序列化/反序列化默认(非自然)行为。

To "force" natural keys in dumpdata you can create a shell alias.要在dumpdata “强制”自然键,您可以创建一个 shell 别名。

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.如果您需要更高级的模型序列化/反序列化,我建议您使用外部组件,如Django REST Framework 序列化程序或编写自己的一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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