Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: use custom methods for queryset values()

I am trying to use a custom method from a model as field in value method of QuerySet object.

The model:

class MyModel(models.Model):
    field1
    field2
    field3
    ...

    def custom_method(self):
        return 'somestring'

In another module, I am trying this:

MyModel.objects.all().values('field1', 'field2', 'custom_method').annotate(field3Tot= Sum('field3'))

I need to group the sum by field1, field2 and the custom_method. Is this possible or I have to use only "real" fields like field1...?

like image 592
toscanelli Avatar asked Nov 11 '13 13:11

toscanelli


People also ask

How does QuerySet work in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

What is Select_related in Django?

Using select_related() Django offers a QuerySet method called select_related() that allows you to retrieve related objects for one-to-many relationships. This translates to a single, more complex QuerySet, but you avoid additional queries when accessing the related objects.


1 Answers

You can't.
values() return resultset as per fields passed into it for that model. It will not work if if you will pass any custom methods.

like image 186
Prashant Gaur Avatar answered Oct 01 '22 14:10

Prashant Gaur