0
votes

Hi have been working with Django and i want to have relations bettwen model i have the following structure

enter image description here

on posts/models.py

from django.db import models
class Post(models.Model):

(SKIP ATTRIBUTES)

and then on comments/model.py
from django.db import models
from posts.models import Post

class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')

In a nutshell im trying to import posts model into comment model and i get the error that cannot import name 'Post' from 'posts.models , how should import posts model to avoid this issue ?

from posts.models import Post ImportError: cannot import name 'Post' from 'posts.models

2
Your structure and import statement seems fine. Make sure, you have saved your files, and try restarting the server.darshanc99
Also, have you added your Post model in the admin.py of the posts app?darshanc99
@DarshanChheda yes ,i have my Post model on admin.py the strange thing here is that from posts.models import Post its working there but not when i import con Comment modelGuillermo Nahuel Varelli
Please provide the code snippet. Might be some very minor unseen issuedarshanc99

2 Answers

1
votes

If you are also importing comments.models in posts.models, This may happen due to circular import. Try this:

from posts import models as posts_models

and

post = models.ForeignKey(posts_models.Post,on_delete=models.CASCADE,related_name='comments')
0
votes

Try this, tell me if it helps

from DjangoPost.posts.models import Post

instead of

from posts.models import Post