Pinank Lakhani Pinank Lakhani - 1 month ago 23
Python Question

Import serializer in models.py : Django rest framwork

My one model class having following models,

NewsfeedModel.py

class NewsFeed(models.Model):

class NewsStatus(models.Model):

class NewsImage(models.Model):


this is my serializers.py file

from MadhaparGamApps.AppModels.NewsfeedModel import NewsFeed, NewsStatus, NewsImage

class NewsFeedSerializer(serializers.ModelSerializer):


Up to this, it's working fine I'm able to use models in serializer. Now I have to use serializer in my NewsfeedModel file, so I import serializer in NewsfeedModel file, but it's not allowing me to use.

getting following error in the log:

ImportError: cannot import name NewsFeed


Is there any way to use serializer in model class?

Answer

The way to work around a circular import is to remove one of the imports from the module level and do it inside the method where it is used.

You haven't shown all the model code so I don't know where you use it, but if it's in save it would look like this:

def save(self, **kwargs):
    import serializers
    # rest of method