Home > database >  How to select related objects with only one query
How to select related objects with only one query

Time:08-31

Models:

class Tag(BaseModel):
    tag_name = models.CharField(max_length=250)
    slug = models.SlugField()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.tag_name)
        super(Tag, self).save(*args, **kwargs)

    def __str__(self):
        return str(self.tag_name)


class Tags(BaseModel):
    filtertype = models.CharField(max_length=250)
    tags = models.ManyToManyField(Tag)

My current solution:

    def get(self,request,version):
        filtertype = request.query_params.get('filtertype', '')
        filtertypes = filtertype.split(",")


        tagsList = Tags.objects.filter(filtertype__in=filtertypes).values_list('tags', flat=True).distinct()
        queryset = Tag.objects.filter(id__in=tagsList)

        context = {"request": request}
        serialized = TagListSerializers(queryset, many=True, context=context)
        return Response(serialized.data)

Im trying to get all the relevant Tag base on Tags/filtertype. Im wondering how can I do it with only one query.

CodePudding user response:

you can do the query part with this code:

queryset = Tag.objects.filter(tags__filtertype__in=filtertypes)
  • Related