Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Value Error. Cannot assign query set. It must be an instance

I want to create object in my comment model. It's my Reply model to a post.

class Reply(MPTTModel):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

    detail = models.CharField(max_length=50, null=True, blank=True, unique=True)

    pub_date = models.DateTimeField(auto_now_add=True)
    last_edited = models.DateTimeField(auto_now=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    class MPTTMeta:
        order_insertion_by = ['name']

It's my view function for reply.

def post_detail(request,id,**kwargs):
    post = Post.objects.all().filter(id=id)
    comment = CommentReply.objects.filter(post=id)
    context = {'post': post, 'comment': comment}
    if request.method == 'POST':
        comments = request.POST.get('comment')
        Reply.objects.create(
                post=post, detail=comments, author = request.user)
    else:
        return render(request, 'khalidblog_app/full_detail.html', context)

    return render(request,'khalidblog_app/full_detail.html',context)

I'm using for loop in my template:

{% for post in post %}
    <img alt='' src='{{ post.image.url }}' class='avatar avatar-80 photo' height='80' width='80' />
    <div class="eltd-author-description-text-holder">
        <h5 class="eltd-author-name"> {{post.author}} </h5>
    <div class="eltd-author-text">
        <p>{{post.title}}</p>
    </div>
    <div class="eltd-author-text">
        <p>{{post.content}}</p>
        <hr>
    </div>
{%endfor%}

When I run this view function It shows a value error as follows.

Cannot assign "<QuerySet [<Post: Author : zorainTiTleFirst PostDated :2021-01-17 16:27:47.043869+00:00>]>": "Reply.post" must be a "Post" instance.

How I can set the forignkey(Post) in this reply model using this view function?

question from:https://stackoverflow.com/questions/65943713/value-error-cannot-assign-query-set-it-must-be-an-instance

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

1 Answer

0 votes
by (71.8m points)

On the very first line of your function, you are using .filter() method which returns QuerySet (List of Objects in short), where you should have ideally used .get() method. .get() returns a single object which the assignment on line 6 actually expects.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...