Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using absolute function in Django query set order by clause

I have a simple queryset that uses the following model:

class question(models.Model):
question_id = models.AutoField(primary_key=True) # Field name made lowercase.
question = models.TextField() # Field name made lowercase.
type = models.IntegerField() # Field name made lowercase.    
difficulty = models.DecimalField(max_digits=12, decimal_places=10)

The queryset is defined as:

...
theta=10
q=question.object.filter(type=1).order_by(abs('difficulty'-theta))

I receive a TypeError: cannot concatenate 'str' and 'int' objects

The equivalent SQL works. However I would like to use standard django ORM if I can.

select * from quiz_question where type=1 order by abs(difficulty-10)

I have tried to use the extra() method. Specifically the select argument to specify the equation, and the order_by argument to do the ordering.

...
theta=10
q=question.object.filter(type=1).extra(select={'diff': abs('difficulty-10')}).extra(order_by=['diff'])

I get a bad operand type error. Any good ideas?

like image 533
user2109249 Avatar asked Dec 02 '25 02:12

user2109249


1 Answers

q = question.object.filter(type=1).extra(
    select={"diff": "abs(difficulty-10)"}).order_by("diff")
like image 148
mVChr Avatar answered Dec 04 '25 16:12

mVChr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!