1

I'm trying to write the following query in Django/Python: in this query, I don't have a simple or, but I have many ands also and a sum

SELECT sum(value) FROM myapp_category
WHERE (name='difficulty' AND key='hard')
   OR (name= 'success' AND key='yes')
   OR (name= 'alternative' AND key='yes')
   OR (name= 'processing' AND key='good')
   OR (name= 'personal_touch' AND key='yes') `

and here's my model:

class Category(models.Model):
   name = models.CharField(max_length=50)
   key = models.CharField(max_length=30)
   value = models.FloatField(blank=True, default=0)

   def __str__(self):
      return self.name.encode('utf_8') + "_" + self.key.encode('utf_8')

and I don't want to use the raw sql, so what can I use for this ?

Update Answer: Thanks for your answers, this is the complete answer:

    sum = Category.objects.filter(Q(name='difficulty',key=evaluation.difficulty) | 
Q(name='nogos',key=evaluation.nogos) | 
Q(name='success',key=evaluation.success) | 
Q(name='alternative',key=evaluation.alternative) | 
Q(name='processing',key=evaluation.processing) | 
Q(name='personal_touch',key=evaluation.personal_touch))
.aggregate(result=Sum('value'))

    score = float(sum['result'])
Safaa Na
  • 23
  • 4

3 Answers3

1

Try this;

from django.db.models import Q, Sum


Category.objects.filter(Q(name='difficulty',key='hard') | Q(name='success',key='yes') | Q(name='alternative',key='yes') | Q(name='processing',key='good') | Q(name='personal_touch',key='yes')).aggregate(Sum('value'))
Geo Jacob
  • 5,909
  • 1
  • 36
  • 43
0

UPD

from django.db.models import Q

results = Category.objects.filter(
    Q(name="difficulty", key="hard") | Q(name= "success", key="yes") | 
    Q(name="alternative", key="yes")|Q(name="processing" AND key="good") | 
    Q(name="personal_touch",key="yes"))
ivan K.
  • 207
  • 1
  • 7
0

Not really a solution but maybe input for other ideas:

SELECT sum(value) FROM myapp_category
WHERE name+"/"+key IN (
  'difficulty/hard',
  'success/yes',
  'alternative/yes',
  'processing/good',
  'personal_touch/yes'
)

Problems:

  • Also lists cannot be provided using parameters
  • The query is slower because indexes cannot be used
Daniel Alder
  • 5,031
  • 2
  • 45
  • 55