Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
99 views
in Technique[技术] by (71.8m points)

python - 'QuerySet' object has no attribute 'friends'

I am building a BlogApp and I was building a Feature BUT i am stuck on a Error.

when i open Detail page then i keep getting :-

'QuerySet' object has no attribute 'friends'

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True)
    friends = models.ManyToManyField("Profile",blank=True)

    def __str__(self):
        return f'{self.user.username}'

CHOICES = (
    ('everyone','Every One'),
    ('friend','friend only'),
    ('none','Nobody'),
)

urls.py

path('<id>',views.detail_view,name='detail_view'),

Explanation of views.py

My code is supposed to , When i click on friends only then it should check request.user friends list AND if request.user is exist then comment form will show. BUT this is keep showing me 'QuerySet' object has no attribute 'friends' Error.

The Problem

When i put 'allow_comments == friend' in views and select friend only in Browser then i got this error.

Any help would be appreciated.

Thank You in Advance

question from:https://stackoverflow.com/questions/65901498/queryset-object-has-no-attribute-friends

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You save a whole QuerySet in the variable user. A QuerySet is always an instance of QuerySet. This is why the object saved under the name user does not have the attributes that an instance of Profile would have.

You should for clarity save the user-object in the variable user and rename that ForeignKey in Post to author. To get the corresponding instance of Profile you can use the reverse of the OneToOneField you defined:

models.py:

...
class Post(models.Model):
    author = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE)

views.py:

def detail_view(request,id):
    ...
    user = request.user
    ...
    elif (
        post.allow_comments == 'friend'
        and user.is_authenticated
        and user.profile is not None
        and user.profile in post.author.profile.friends.all() 
    ):
        ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...