1

I am trying to use the F() for my queryset

I had my previous question about using F() in F() expressions in django keeps giving me 0

but then somehow I figured, I cannot use F()'s length for my function. At first I did not get why then I figured ending up I was trying to do len(F()) which is why I am getting error since F() is type of <class 'django.db.models.expressions.F'> instead of a string or number type.

Is there a way to get the F() value so I can use len(F())?

Thanks in advance for any help.

Dora
  • 6,776
  • 14
  • 51
  • 99

1 Answers1

0

As long as you want this to be a single query in database, you have to use SQL, so you cannot just apply arbitrary python functions. To take a length of char column there is a Length expression in Django(https://docs.djangoproject.com/en/1.11/ref/models/database-functions/#django.db.models.functions.Length), which you can use like this Length(F('name')). It will add necessary code to generated SQL so database do the right thing.

So finally, if you need for example to set some column to the length of another column value, you can use Model.objects.update(name_length=Length(F('name')))

Alexandr Tatarinov
  • 3,946
  • 1
  • 15
  • 30
  • then I guess what I wanted to do `F()` is not the right one to use. which means my other question is actually not answered but already marked correct by me >.<" – Dora May 22 '18 at 23:46