[파이썬] mongoengine 커스텀 필드 정의하기

Mongoengine is a powerful Object-Document Mapper (ODM) for working with MongoDB in Python. It provides a simple and intuitive way to define and work with MongoDB documents.

One of the key features of mongoengine is the ability to define custom fields to handle specific data types or behaviors. In this blog post, we will explore how to define custom fields in mongoengine to suit our application’s needs.

Why Define Custom Fields?

Mongoengine provides a wide range of built-in fields to handle common data types like strings, integers, dates, etc. However, there may be cases where the default fields are not sufficient for our requirements. In such cases, defining custom fields allows us to extend mongoengine’s functionality and tailor it specifically for our application’s needs.

Defining a Custom Field

To define a custom field in mongoengine, we need to create a new class that inherits from the mongoengine.fields.BaseField class. This new class will encapsulate the logic and behavior of our custom field.

Here’s an example of how to define a custom field called EmailField that validates and stores email addresses:

from mongoengine.fields import StringField

class EmailField(StringField):
    def validate(self, value):
        super().validate(value)
        
        # Custom validation logic for email addresses
        if not value.endswith('@example.com'):
            raise ValidationError('Invalid email address')
    
    def to_python(self, value):
        # Additional processing logic before storing the value
        return value.lower()

In the example above, our EmailField inherits from the StringField provided by mongoengine. We override two methods: validate() and to_python().

The validate() method is used to add custom validation logic to our field. In this case, we are ensuring that the email address ends with @example.com. If the validation fails, we raise a ValidationError.

The to_python() method is used to process the value before storing it in MongoDB. In this example, we convert the email address to lowercase before storing it.

Using the Custom Field

Once we have defined our custom field, we can use it in our mongoengine document classes like any other field. Here’s an example of how to use our EmailField:

from mongoengine import Document

class User(Document):
    email = EmailField()

In the example above, we define a User document class with an email field of type EmailField. When saving a User instance, mongoengine will automatically validate the email field using our custom validation logic and store the lowercased email address in MongoDB.

Conclusion

Defining custom fields in mongoengine allows us to extend its functionality and adapt it to meet our application’s specific needs. By creating our custom field classes, we can easily handle complex data types or implement custom validation logic.

Mongoengine’s flexibility and ease of use make it a great choice for working with MongoDB in Python, and the ability to define custom fields further enhances its power.

Happy coding with mongoengine and your custom fields!