Opened 9 years ago

Closed 9 years ago

#23928 closed Bug (needsinfo)

Raw queryset and use inner join

Reported by: Ivan Owned by: nobody
Component: Database layer (models, ORM) Version: 1.7
Severity: Normal Keywords: raw, select_related
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

when I used raw queryset I was faced with incorrect mapping of fields in the output if the sql query was attended by JOIN. [id, name, test id, key] returns a field from a mysql cursor, due to duplication of columns was offset to get the value of id!

I temporarily have corrected this by extracting the first occurrence of the name column:

Note the line "if column not in model_init_field_names:"

class MyRawQuerySet(RawQuerySet):

    def __iter__(self):
        # Mapping of attrnames to row column positions. Used for constructing
        # the model using kwargs, needed when not all model's fields are present
        # in the query.
        model_init_field_names = {}
        # A list of tuples of (column name, column position). Used for
        # annotation fields.
        annotation_fields = []

        # Cache some things for performance reasons outside the loop.
        db = self.db
        compiler = connections[db].ops.compiler('SQLCompiler')(
            self.query, connections[db], db
        )
        need_resolv_columns = hasattr(compiler, 'resolve_columns')

        query = iter(self.query)

        try:
            # Find out which columns are model's fields, and which ones should be
            # annotated to the model.
            for pos, column in enumerate(self.columns):
                if column not in model_init_field_names:
                    if column in self.model_fields:
                        model_init_field_names[self.model_fields[column].attname] = pos
                    else:
                        annotation_fields.append((column, pos))

Change History (1)

comment:1 by Anssi Kääriäinen, 9 years ago

Resolution: needsinfo
Status: newclosed

It isn't clear how to reproduce the error you are seeing from the description. Could you post example models and the raw query that is causing the problem for you. I'll close this needsinfo, please reopen when you provide the additional information.

Note: See TracTickets for help on using tickets.
Back to Top