1

I have a model like this:

class Priority(models.Model):
    base = models.FloatField(default=0)
    job = models.JSONField()
    users = models.JSONField()

and both job and users are similar.

like job = {'a':1,'b':2}, user = {'c':3,'d':4}

I want to get the sum ( base + job__a + users__c)

how can I write the filter statement,

and raw sql is fine too.

Thanks

1 Answer 1

2

You should accomplish this (updated):

    queryset = Priority.objects.annotate(
        a=Coalesce(
            Cast(KeyTextTransform('a', 'job'), output_field=FloatField()),
            Cast(V(0.0), output_field=FloatField())
        ),
        c=Cast(KeyTextTransform('c', 'users'), output_field=FloatField()),
    ).annotate(
        sum=Sum(
            F('base') + F('a') + F('c'), output_field=FloatField() 
        )
    )

    for item in queryset:
        print(item.sum)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks ,if the key(a) is not in the json Field(job), and I want to give a default value (0.0.),how to handle this ?
You can use F('a')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.