0

I have the following models

class Question(models.Model):
 content=models.TextField()
 ...
class Answer(models.Model):
 created_at = models.DatetimeField(auto_add=True)
 author = models.ForeignKey(User, ... )
 content = models.TextField()
 question = models.ForeignKey(Question, ....)
 ...
 class meta:
 unique_together=('author','question')

in the database I have a set of questions and answers. answers are linked to their authors. unique_together ensures the user can give an answer only once to a question.

usr_1 Is a user instance that has answers to some questions that I can retrieve by:

qst_qs=Question.objects.filter(answer__author=usr_1)

I want to sort questions in qst_qs according to the created_at field in usr_1's answer in each question.

Thanks in advance.

asked Jul 22, 2020 at 16:24

2 Answers 2

0

Use an annotation for usr_1’s answer timestamp, then order by it:

from django.db.models import Max
qst_qs = (Question.objects.filter(answer__author=usr_1)
     .annotate(user_answer_created_at=Max("answer__created_at"))
     .order_by("-user_answer_created_at"))

annotate() adds the per-question answer time (for that user), and order_by() sorts by it.

DaveL17
2,08112 gold badges30 silver badges48 bronze badges
answered Dec 17, 2025 at 16:49
Sign up to request clarification or add additional context in comments.

Comments

-1

Please try this code:

qst_qs=Question.objects.filter(answer__author=usr_1).order_by('answer__created_at')
Dima Kozhevin
3,77210 gold badges43 silver badges54 bronze badges
answered Aug 7, 2020 at 15:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.