Allow database API users to specify the fields to exclude in a SELECT statement
|Reported by:||Adrian Holovaty||Owned by:||Malcolm Tredinnick|
|Component:||Database layer (models, ORM)||Version:||master|
|Cc:||Manuel Saelices, ferringb@…, Marinho Brandão, semente@…, research@…, youngj@…, Ian Kelly, Alexander Koshelev, flosch@…||Triage Stage:||Accepted|
|Has patch:||yes||Needs documentation:||yes|
|Needs tests:||no||Patch needs improvement:||yes|
This one will help people use their databases more efficiently.
The Django ORM should allow users to specify a list of field names to *exclude* from a
QuerySet. If a user attempts to access one of those excluded fields on the resulting model instance, the field will be loaded lazily via a separate query.
This is useful when you know you absolutely will not need to use a particular field in your template, so there's no point in SELECTing that data. This saves memory, and it saves on bandwidth between the database server and the Web server.
class Person(models.Model): name = models.CharField(maxlength=32) age = models.IntegerField() hometown = models.CharField(maxlength=32) is_cool = models.BooleanField() # My instinct is to call this hide(), but I'm sure there's a better name for it. >>> p = Person.objects.hide('hometown', 'is_cool').get(name='John Lennon') >>> p.id 3 >>> p.name u'John Lennon' # Does a query to get "hometown", because it was hidden from the QuerySet. # 'SELECT hometown FROM person WHERE id=3;' >>> p.hometown u'Liverpool' # Does a query to get "is_cool", because it was hidden from the QuerySet. # 'SELECT is_cool FROM person WHERE id=3;' >>> p.is_cool True
In the case of lazily loaded fields, the lazy loading *only* applies to the particular field. E.g., when I accessed
p.hometown in the above example, it did *not* also lazily load the rest of the hidden fields ("is_cool").
We should also provide the inverse of
hide() -- perhaps called
expose()? -- which would take a list of field names to *include* rather than *exclude*. This would be an opt-in instead of an opt-out.
Change History (34)
comment:23 Changed 9 years ago by
|Owner:||changed from Jacob to Malcolm Tredinnick|
|Status:||assigned → new|