SoFunction
Updated on 2024-11-21

Django JSONField automatic conversion ideas in detail (django custom model fields)

Django JSONField auto-conversion (django custom model fields)

contexts

One of the major updates to Django v3.1 is improved support for JSON data stores, with the addition of and , available on all supported database backends.

You can specify this field as a storage type in JSON format. null=True means that this field can be null.

from  import models
class Hello():
    name = (max_length=200)
    data = (null=True)
    def __str__(self):
        return 

reasoning

If you want to implement automatic JSONField conversion, you can either use the Django REST framework's JSONField, or customize a field class and override the from_db_value() and get_prep_value() methods to achieve this functionality.

DRF JSONField is simpler, but relatively more complex to use. Custom field class is more lightweight, but we need to complete a certain amount of coding work.

The recommended method here is to use a custom field class!

JSONField with DRF

To use DRF JSONField, mainly in the Serializer imported and applied to the need for automatic conversion of JSON fields , and then serialized and deserialized in the view , JSONField will automatically complete all the conversion work associated with it .

Customize a field class and override the from_db_value() and get_prep_value() methods

Using JSONField directly will not convert automatically because.

  • JSONField is simply a field that inherits from TextField.
  • It does not itself implement the from_db_value() and get_prep_value() methods
  • So when we access it, we only get a JSON encoded string, not a Python object.
  • It also doesn't automatically reconvert Python objects to JSON strings when saving the instance

Overriding the from_db_value() and get_prep_value() methods of a model field can achieve the 'auto-conversion' effect.

  • The from_db_value() method is used to convert a value to a Python object when reading from a database.
  • The get_prep_value() method is used to convert a Python object to a value before the database saves the value
    By overriding these two methods, we can implement customized conversion logic to achieve the effect of automatic conversion.

django custom model fields @models.register_field()

@models.register_field() is a model registration decorator. Use it to register a custom field so that it can be used in the model like a built-in field.

For example, a JSONField that uses this decorator can be used in a model like this.
python
class Product():
info = ()
Instead of importing field classes: the
python
from .fields import JSONField

class Product():
info = JSONField()

To summarize: in this case, we don't need to import the field class separately (we just need to import JSONField in the django startup portal, e.g. The purpose is to use [email protected]_fieldThe decorator registers this field,exposeDjangoKnows and can be used like a built-in field in any model). If we don't use this decorator, we have to import the field class before we can use it in the model.

additionally,Even with the use [email protected]_fielddecorator,We can also directly importJSONFieldfield class and use it in the model.

Example: imported, and then introduced this JSONField separately in the concrete model class, which one is used?
In this case, Django uses the JSONField field class that you imported directly in the model.
In other words, the import in the model is ignored and the field classes imported in the model take effect and are actually used in the model.
This is because.

  • Django resolves which field class is actually used, not which is imported.
  • If the same field class is imports twice, Python will only use the last one imported.

[email protected]_field() brings the following benefits.

  • Make the use of custom fields look like built-in fields, more concise and direct, easy to understand.
  • No need to import custom field classes , the model can be defined independently , decoupled from the field import dependency .
  • Automatically handles field parameters without passing them in the model, using them like built-in fields.
  • Convenient integration with third-party libraries, allowing the use of third-party-supplied custom fields directly in the model.

Another point to note is that You are using [email protected]_fielddecorator,commander-in-chief (military)JSONFieldRegistering for a model field that can be used like a built-in field.
However, Django needs to import this field class when it is first run to know what field JSONField represents.
So, you need to import this field class in the model corresponding to the model that uses JSONField for the first time.

After testing Django-4.2.1, there is no register_field decorator.

Therefore, in summary, the direct definition of custom model field class, when using a separate introduction can be, this also does not pollute the environment (do not have to import once without the use of the IDE also reported gray), that is, that can be used, the feeling is clearer.

to this article on the automatic conversion of Django JSONField (django custom model fields) of the article is introduced to this , more related django custom model fields content please search my previous posts or continue to browse the following related articles I hope you will support me more in the future !