'How to annotate to query with a custom function in Django ORM?
I have this model:
class Brand(models.Model):
name = models.CharField(max_length=32)
and this function that returns a number that shows similarity between two strings (a number between 0 and 1).
from difflib import SequenceMatcher
def similar(a, b):
return SequenceMatcher(None, a, b).ratio()
I want to annotate a column to my query that shows similarity value between name and a string and order them by similarity.
I wrote something like this but it won't work and I don't know how it works.
Brand.objects.all().annotate(
similarity=ExpressionWrapper(similar(F('name'), 'mercedes'),
output_field=models.DecimalField()).order_by('similarity')
)
If there is another way to do it please let me know.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
