我正在为简单的问答论坛开发网站。我想获得答案。
models.py
class Answer(models.Model):
ans = models.TextField()
img = models.CharField(max_length=100)
created_by = models.ForeignKey(User, related_name='answer')
created_on = models.DateTimeField(auto_now_add=True)
ques = models.ForeignKey(Question, related_name='answer')
def __str__(self):
return self.ans
class Upvote(models.Model):
upvote = models.BooleanField(default=False)
upvote_by = models.ForeignKey(User, related_name='upvote')
upvoted_on = models.DateTimeField(auto_now_add=True)
#ques = models.ForeignKey(Question, related_name='upvote')
ans = models.ForeignKey(Answer, related_name='upvote')
def __str__(self):
return self.upvote_by
views.py
我可以获得如下答案的赞成票
answer = get_object_or_404(Answer, pk=1)
upvotes = Upvote.objects.filter(ans=answer)
如何从答案对象中获取回报?如果我错了,请纠正我。如下所示,
answer.upvote_set
提前致谢!!
答案 0 :(得分:1)
鉴于您在模型中显示的此字段:
A Event 1 Event 2 Event 3
B Group 1 Group 2
你可以访问这样的答案的赞成票
class Upvote(models.Model):
# ... other code ...
ans = models.ForeignKey(Answer, related_name='upvote')
# ... other code ...
如果您将字段定义更改为此(删除answer_instance.upvote.all()
):
related_name
您应该能够使用您询问的代码:
ans = models.ForeignKey(Answer)