Home > other >  Get queryset with only selecting one object in related to foreign key
Get queryset with only selecting one object in related to foreign key

Time:11-29

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 trying this way but this doesn't have any affect

def get_queryset(self, request):
        qs = super().get_queryset(request)
        idx = list(qs.values_list("survey_id", flat=True).distinct())

        return qs.filter(survey_id__in=idx).distinct()

Edit: I'm now able to do it this way, but I'm not sure if that is optimal solution. your suggestions are welcome to improve it.

 def get_queryset(self, request):
        qs = super().get_queryset(request)
        idx = list(qs.values_list("survey_id", flat=True).distinct())

        data = []
        for i in qs:
            if i.survey_id in idx:
                data.append(i)
                idx.remove(i.survey_id)

        # modify the data to queryset
        return qs.filter(pk__in=[i.pk for i in data])

CodePudding user response:

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)
  • Related