In Django, Can I `defer()` fields in an object that's being queried by `select_related()`
Asked Answered
H

1

11

In my Django app I want to use select_related() on a QuerySet to "follow" a ForeignKey field, but I only need to access a few of the fields on the "followed" model instance. Can I use the defer() method somehow with my "followed" field.

e.g., if I have...

class BarModel(models.Model):
    ...
    blah = models.TextField()

class FooModel(models.Model):
    bar = models.ForeignKey(BarModel)
    ...    

...and I'm doing FooModel.objects.all().select_related('bar') how can I defer() the field blah.

Thanks.

Heavyfooted answered 7/5, 2011 at 4:2 Comment(0)
H
15

Using Django's double-underscore notation as shown here.

FooModel.objects.all().select_related('bar').defer('bar__blah', ...)
Hangdog answered 7/5, 2011 at 4:32 Comment(1)
Note: currently there is an opened issue with select_related for o2o relationship and 'only()' method ('defer' works fine). code.djangoproject.com/ticket/23051 (maybe would be useful for somebody)Cyanosis

© 2022 - 2024 — McMap. All rights reserved.