Opened 7 years ago

Closed 7 years ago

Last modified 5 years ago

#11381 closed (fixed)

select_related over nullable ForeignKey using GeoQuerySet and GeoManager gives blank object rather than None

Reported by: Brett Hoerner Owned by: nobody
Component: GIS Version: 1.1-beta
Severity: Keywords: geodjango geo select_related geomanager
Cc: dgouldin@… Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: yes Patch needs improvement: no
Easy pickings: UI/UX:


Sorry for the bad title... I can only explain this with an example,

from django.contrib.gis.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

class BookManager(models.GeoManager):
    def get_query_set(self):
        return super(BookManager, self).get_query_set().select_related('author')

class Book(models.Model):
    name = models.CharField(max_length=100)
    author = models.ForeignKey(Author, related_name="books", null=True, blank=True)

    objects = BookManager()
>>> Book.objects.create(name='Without Author')
<Book: Book object>

>>> b = Book.objects.get(name='Without Author')

<Author: Author object>


As you can see, rather than being None, is it an "empty" Author object. This isn't the case when using non-GeoDjango.

What's even weirder is that this only happens when using the GeoManager. If you remove the manager and run the select_related yourself, the following happens,

>>> Book.objects.select_related('author').get(name='Without Author').author

It's None, rather than the "empty" Author from above.

Attachments (1)

11381.diff (501 bytes) - added by David Gouldin 7 years ago.

Download all attachments as: .zip

Change History (7)

comment:1 Changed 7 years ago by David Gouldin

Cc: dgouldin@… added
Needs documentation: unset
Needs tests: unset
Patch needs improvement: unset

comment:2 Changed 7 years ago by David Gouldin

Looks like the row being passed to django.db.models.query.get_cached_row is a list, not a tuple, which causes fields == (None,) * field_count to always fail. Thus obj is instantiated at times it should be set to None.

Changed 7 years ago by David Gouldin

Attachment: 11381.diff added

comment:3 Changed 7 years ago by David Gouldin

Has patch: set

comment:4 Changed 7 years ago by Alex Gaynor

Needs tests: set
Triage Stage: UnreviewedAccepted

comment:5 Changed 7 years ago by jbronn

Resolution: fixed
Status: newclosed

(In [11123]) Fixed #11381 -- GeoManager + select_related + nullable ForeignKey now works correctly. Thanks, bretthoerner for ticket and dgouldin for initial patch.

comment:6 Changed 5 years ago by Jacob

milestone: 1.1

Milestone 1.1 deleted

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