-1

Goal: use a related model attribute as a filter inside a conditional expression for an annotation.

I'm currently adding some functionality to an old Django app, this app has some design issues and i have nothing to do with it. After some research I found conditional expressions, this is great and what I needed.

However I'm not being able to make it.

Let's have model A, model B and model C.

class ModelA(models.Model):
    name=models.Charfield()
    reference=models.ForeignKey('app.ModelB')

class ModelB(models.Model):
    name=models.Charfield()

class ModelC(models.Model):
    name=models.Charfield()
    reference=models.ForeignKey('app.ModelB', related_name='some_reference')
    bool_field=models.BooleanField()

And this is what I would like to do:

ModelA.objects.all().annotate(some_field=When(Q(reference__some_reference__bool_field=True), 
                                                then=F('reference_some_reference_name')))

This should work since it is being interpreted by python, but I get some Syntax Error from MySQL. What am i doing wrong? Is this even possible?

This is what I'm getting:

django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHEN `ParametrosPreciosProveedor`.`already_iva` = 1 THEN `ParametrosPreciosProve' at line 1")

'ParametrosPreciosProveedor' is ModelC in this example and 'already_iva' is bool_field.

1 Answers1

0

I would try removing the When and then parts of the annotation. Q objects do those automatically - you don't define those terms in Python.

ModelA.objects.all().annotate(some_field=Q(reference__some_reference__bool_field=True), 
                          F('reference_some_reference_name')))

Check out the docs to see how to use Q()