Django:'思考'对象没有属性' choice_set' - 无法访问选择集

时间:2015-09-25 20:41:14

标签: python django django-models django-views

在我的模型中,我定义了一个思考和评论模型。一个想法有很多评论如此:

class Thoughts(models.Model):
    name = models.CharField(max_length=30)
    thought = models.CharField(max_length=500)

class Comments(models.Model):
    name = models.CharField(max_length=30)
    comment = models.CharField(max_length=200)
    original_post = models.ForeignKey(Thoughts, default=0)

在我的网站上,当你去查看一个想法时,我希望所有的评论都出现。我的理解是,您可以使用choice_set通过一对多关系访问属性。以下是我的观点:

def thought(request, thought_num):
        if request.method == 'POST':
            form = CommentForm(request.POST)
            if form.is_valid():
            c = Comments.objects.create(name=form.cleaned_data['name'],
                comment=form.cleaned_data['comment'])
            c.save()
    else:
        form = CommentForm()

    get_post = Thoughts.objects.get(pk=thought_num)
    comments = get_post.choice_set.all()
    return render(request, 'thought.html', {'form': form, 'comment':comments,})

在这些行中,我尝试访问与特定思想相关的所有评论,以便在我的模板中打印它们。

    get_post = Thoughts.objects.get(pk=thought_num)
    comments = get_post.choice_set.all()

当我访问应该显示评论的页面时,我收到此错误:

Exception Type: AttributeError
Exception Value:'Thoughts' object has no attribute 'choice_set'

也许我错过了什么,我不确定。我确定它很简单。谢谢你的时间

2 个答案:

答案 0 :(得分:1)

检索与思想相关的所有评论。您可以执行以下操作:

Thoughts.objects.get(pk=thought_num).comments_set.all()

如果要覆盖默认的related_name(" comments_set")。您可以执行以下操作: original_post = models.ForeignKey(Thoughts, default=0, related_name='choice_set')

答案 1 :(得分:0)

当你创建一个ForeignKey时,默认的相关名称将成为当前类的小写名称+“_ set”,因此对于你的项目应该是:

get_post = Thoughts.objects.get(pk=thought_num)
comments = get_post.comments_set.all()

或者您甚至可以创建自定义相关名称而不是默认名称:

class Thoughts(models.Model):
    name = models.CharField(max_length=30)
    thought = models.CharField(max_length=500)
    class Thoughts(models.Model):
    name = models.CharField(max_length=30)
    thought = models.CharField(max_length=500)

class Comments(models.Model):
    name = models.CharField(max_length=30)
    comment = models.CharField(max_length=200)
    original_post = models.ForeignKey(Thoughts, default=0, related_name='comments')

所以你可以得到这样的评论:

get_post = Thoughts.objects.get(pk=thought_num)
comments = get_post.comments.all()