[Answered ]-Django query for string literal that starts with field value

1👍

You can "inject" the value with .alias(…) [Django-doc] and then use the __istartswith lookup [Django-doc] in the opposite order:

from django.db.models import F, Value

ContentType.objects.alias(val=Value('MyModelNode')).filter(
    val__istartswith=F('model')
)

This will thus retrieve ContenTypes with as model, the empty string '', 'M', 'My', etc.

That being said, if you just want to remove the last four characters, you use:

ContentType.objects.filter(val__istartswith='MyModelNode'[:-4])

this will construct a string with the last four characters removed, so `’MyModel’` instead of `’MyModelNode’`.

Leave a comment