Get queryset with only selecting one object in related to foreign key
I have a model named Answer
class Answer(models.Model):
survey = models.ForeignKey(Survey)
I want to return a queryset of Answer according to Survey foreign Key, Means if there are 3 objects ,
answers = [
{"survey": 1},
{"survey": 2},
{"survey": 1},
]
then queryset should return
[
{"survey": 2},
{"survey": 1},
]
Means that will check if there is Answer with a foreign key then it should not select other Answer with same foreignkey. So how to do that. I'm doing this for django admin page.
super().get_queryset(request).filter(
# filters
)
you could do it like this with less for loops as possible (always rely on database not in the for loops):
for id in idx:
new_value = qs.filter(survey_id=id).first()
data.append(new_value)