#22766 closed New feature (duplicate)
Model derivated fields
Reported by: | Owned by: | nobody | |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | dev |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
It could be useful to allow a query to fetch additional fields for a bulk of objects.
Assume I have class Person as follows:
class Person(Model):
first_name = CharField(max_length=30)
last_name = CharField(max_length=30)
@property
def full_name(self):
return self.first_name + ' ' + self.last_name
It's useful to have this propert but: what about serializing a large bulk of objects? E.g. generating:
["John Lennon", "George Harrison", "Paul McCartney", "Ringo Starr"]
Assuming I have a bigger list (1000+ entries for some reason), this would require iterating over the whole list:
return JSONResponse([person.full_name for person in Person.objects.all()]) #assume I have such object
My proposed solution is to have another queryset method like the "annotate()" but instead of fetching a statictical value from related objects, get a derivated value from the same object. It could be:
Person.objects.all().derivated(full_name=F('first_name')+' '+F('last_name'))
and even in values() or values_list()
Person.objects.all().values('first_name', 'last_name', full_name=F('first_name')+' '+F('last_name'))
Where the derivated fields come as kwargs.
Change History (3)
comment:1 by , 11 years ago
comment:2 by , 11 years ago
Resolution: | → wontfix |
---|---|
Status: | new → closed |
Version: | 1.6 → master |
I personally don't think this is an important feature, since there are so many ways to do that (you're aware of at least some of them).
Nevertheless, please first request the feature on the django-developers mailing list. It’ll get read more closely if it’s on the mailing list. This is even more important for big feature requests like this one (and pretty much every new feature in the ORM).
Please re-open if the decision after discussion is to implement the feature.
Thanks.
comment:3 by , 11 years ago
Resolution: | wontfix → duplicate |
---|
This idea has been proposed a few times in the past, in one of two guises:
1) A new field on the model that references other fields - much in the same way that a GenericForeignKey field does right now. I'm going to guess there's some details that need to be finessed, but the basic pieces of virtual fields are already in place. See #16508, #373
2) A variation to annotation that doesn't also imply grouping. See #20930, #14030, #11305
Errata: In the previous example, the full_name= could clash with the full_name property. Assume I did not create the method in the second example and, instead, I fetched the value using that alias from database.