Reputation: 11751
I have below two models in my app,
class Question(models.Model):
question_text = models.CharField(max_length=200)
question_author = models.ForeignKey(User, on_delete=models.CASCADE)
q_pub_date = models.DateTimeField('Date Question Published')
def __str__(self):
return self.question_text
class Answer(models.Model):
answer_text = models.CharField(max_length=5000)
answer_author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='ans_auth')
question = models.ForeignKey(Question, on_delete=models.CASCADE)
a_pub_date = models.DateTimeField('Date Answer Published')
def __str__(self):
return self.answer_text
I want to show latest questions on home page in a list. Each item in list will show question text and one answer out of many posted for that particular question. I am able to show question text but I am not able to find a way to get the answer item for every question item in my view below,
def home(request):
latest_question = Question.objects.order_by('-q_pub_date')[:15]
Upvotes: 1
Views: 633
Reputation: 8525
You could get the answer to a specific question with the reverse relation question_instance.answer_set.all()
in views, {{ question_instance.answer_set.all }}
in templates.
To select one answer, you can use slice
, or first()
:
{{question_instance.answer_set.all.0 }} # templates
question_instance.answer_set.first() # views
If you want to add a new field
votes
to the Question and you want the answer which has highest votes?
A property method inside your question model will do it like:
@property
def higher_answer(self):
return self.answer_set.all().order_by('vote').last()
Upvotes: 0
Reputation: 1517
You can access all answers by using the related_name
:
>>> question = Question.objects.get(question_text='random question')
>>> print(question.answer_set.all())
You can read more about this on: https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.ForeignKey.related_name
Upvotes: 1