Skip to content

Instantly share code, notes, and snippets.

@peketamin
Created January 24, 2018 03:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peketamin/059e0a76b7d2518aa1cc0772d13b1e3b to your computer and use it in GitHub Desktop.
Save peketamin/059e0a76b7d2518aa1cc0772d13b1e3b to your computer and use it in GitHub Desktop.
Django ORM: When, Case, F (keyword: zero division error)
from django.db.models import F, Case, When, FloatField
from myapp import models
md = models.MyModel.objects.filter(pk=3).annotate(pr=Case(When(price__gte=40., then=F('price') * 10), default=F('price') / 10, output_fields=FloatField())).first()
In [27]: md.price
Out[27]: 40.7424047560126
In [29]: md.pr
Out[29]: 407.424047560126
md = models.MyModel.objects.filter(pk=3).annotate(pr=Case(When(price__lte=30., then=F('price') * 10), default=F('price') / 10, output_fields=FloatField())).first()
In [32]: md.pr
Out[32]: 4.07424047560126
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment