简体   繁体   中英

How to properly join two Django query sets

I have the following logic implemented in an endpoint.

    def get(self, request, branchName, stack, resultType, buildNumberMIN, buildNumberMAX, format=None):
        try:
            # use ONE query to pull all data
            relevant_notes = Notes.objects.filter(
                branchName=branchName, stack=stack, resultType=resultType)

            # filter on the endpoint parameters (range of numbers)
            requested_range = relevant_notes.filter(
                buildNumber__gte=buildNumberMIN, buildNumber__lte=buildNumberMAX)
            
            # also pull latest note -- regardless of requested range
            latest_note = relevant_notes.latest('buildNumber')

            # join the notes
            return_set = requested_range | latest_note
            #serialize the data
            serializer = serializers.NoteSerializerWithJiraData(
                return_set, many=True)

            return Response(serializer.data)

        except Notes.DoesNotExist:
            return Response({"message": f"No notes found"}, status=404)

Context: the logic is put simply, fetch a range of notes, but also include the latest note based on the url parameters. If the range of notes contains no data, still return latest.

The issue I am facing is

AttributeError at /api/v2/notes/Test/Test/Test/1/2/
'Notes' object has no attribute '_known_related_objects'

It is possible that it does not like that I add attempting to combine a query set with a single object...

The issue here is related to the type of the objects I am attempting to join.

One is a queryset containing many note instances, the other is a single note instance.

Instead of using .latest() I was able to resolve the issue simply by using .filter() as the filter method returns a query set... like so

latest_note = relevant_notes.order_by('-buildNumber')[:1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM