2

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?

Obito
  • 391
  • 3
  • 8
Pinank Lakhani
  • 1,109
  • 2
  • 11
  • 31
  • You don't. Why would you need that ? – Linovia Oct 08 '16 at 15:38
  • I need to return a full newly added newsfeed object in push response when admin saves the news on admin panel. Now the save method is caught in models.py signals.post_save.connect(news_feed_post_save, sender=NewsFeed) Refer following link for more i have posted in my other question why i'm needing this. http://stackoverflow.com/questions/39932802/retrieve-inserted-object-after-save-django-rest-framework thank you – Pinank Lakhani Oct 09 '16 at 11:37

2 Answers2

4

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
Tomas Walch
  • 2,245
  • 1
  • 14
  • 17
0

It seems like you are trying to Import NewsFeed model to itself.

The flow of a django-rest-framework looks like this:

Model > Serializer > View

After getting your serializers done all you need to do Is to import the models and serializers into the views.py file, in which you will create classes/functions to handle the calls to the API. an example for such use will be:

views.py

from newsfeedmodel.py import *
from serializers.pi import *

class NewsFeedViewSet(viewsets.ModelViewSet):
    queryset = NewsFeed.objects.all()
    serializer_class = NewsFeedSerializer

I would reccomend that you read the DRF documentation for better understanding:
http://django-rest-framework.org

idik
  • 872
  • 2
  • 10
  • 19