[Django]-Import Django Model Serializer and Use it in Model's Save Method

3👍

Import the serializer in the method:

# models.py
# no from .serializers import TenantSerializer


class Tenant(models.Model):

    # model fields

    def save(self, *args, **kwargs):
        from .serializers import TenantSerializer

        _ = super().save(*args, **kwargs)
        data = TenantSerializer(self).data
        # do something
        return _


# serializers.py
from .models import Tenant


class TenantSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tenant
        fields = '__all__'

2👍

the error caused by circular import between "models.py" and "serializers.py", this happens when two or more modules try to import eachother.

in this case models.py is importing TenantSerializer from serializers.py and serializers.py is importing "Tenant" from "models.py"

to resolve this you can import TenantSerializer inside save function in model.py:

from .serializers import TenantSerializer

class Tenant(models.Model):

    # model fields

    def save(self, *args, **kwargs):
        from .serializers import TenantSerializer  # Move import inside the function
        _ = super().save(*args, **kwargs)
        data = TenantSerializer(self).data
        # do something        
        return _

I hope this helps you.

Leave a comment