Compute multiple model properties in one call

21 views
Skip to first unread message

Navi Sr

unread,
Sep 15, 2017, 6:05:05 AM9/15/17
to Django users

Hi! I have some Django Model which has two properties:

class M(Model):
   
@property
   
def p1(self):
       
return process_result(SomeModel.objects.filter(val_gt=1))

   
@property
   
def p2(self):
       
return process_result(SomeModel.objects.filter(val_lt=1))



And both used in Django Admin list_lisplay = ('p1','p2',) I want to replace 2 database queries with 1, something like this

class M(Model):

    def some_hook(self): 
        res = SomeModel.objects.all()
        self.p1 = process_result(filter(lambda l:l.val > 10, res))
        self.p2 = process_result(filter(lambda l:l.val < 10, res))

PS: problem with >10 or <10 is just an example for simplification, I am only trying to find a way how to define multiple properties with performing one common database query

Thanks

Message has been deleted

C. Kirby

unread,
Sep 15, 2017, 10:03:51 AM9/15/17
to Django users
You want to minimize the calls because you want to show both properties and have one call that backs both? Are the properties used in some way other than info in the admin? Perhaps do what you did with .all() and lambda, but return a tuple from your method, so:


def p1_p2(self):   
res
= SomeModel.objects.all()

     p1 = process_result(filter(lambda l:l.val > 10, res))

     p2 = process_result(filter(lambda l:l.val < 10, res))
return p1,p2

def p1(self):
return self.p1_p2[0]

def p2(self):
return self.p1_p2[1]


Then you can show p1_p2 in your admin
Reply all
Reply to author
Forward
0 new messages