0

I'm trying to match strings with unexpected additional suffix and then select the database in the string.

Example Model:

class Example(models.Model):
    name = models.CharField(max_length=100, default='abcdef', unique=True)

Code:

string = 'abcdef'
unexpected_suffix = '_d'  # This is random and can be '_e', 'eeee', '321'

_string = '{0}{1}'.format(string, unexpected_suffix)  # abcdef_d

x = Example.objects.get(name__randomlookup=_string)  # randomlookup is just an example

Then the variable x will SELECT the row with a name value of 'abcdef'. Is it possible to just use purely Django ORM with this?

P.S.

icontains and iregex will not solve the problem

Dean Christian Armada
  • 6,724
  • 9
  • 67
  • 116
  • It appears that you are using pure Django ORM, except I'm not sure what the `__lookup` is there for? `lookup` is not a standard Django queryset field lookup. – ChidG Mar 23 '17 at 03:26
  • Sorry about that, it's an example.. I'm wondering if django ORM alone can handle this problem.. Or maybe you have something in mind that might solve this? – Dean Christian Armada Mar 23 '17 at 03:29
  • Ah ok. So your question is whether Django ORM can do queries using a dynamic lookup value? If so, the answer is yes. – ChidG Mar 23 '17 at 03:31
  • Actually, I'm asking how can django orm can match values with suffix – Dean Christian Armada Mar 23 '17 at 03:32
  • OK, thanks for the edits. I understand. You want to match the start of a string and ignore the 'suffix'. You can use the `startswith` or `istartswith` lookup functions https://docs.djangoproject.com/en/1.10/ref/models/querysets/#startswith. – ChidG Mar 23 '17 at 03:43
  • `icontains` too. As well as `iregex`. – Andrey Shipilov Mar 23 '17 at 03:44
  • 1
    That's not gonna work icontains work when there is missing characters from the string that is being looked up – Dean Christian Armada Mar 23 '17 at 04:24
  • You're right. So effectively you want the reverse of `icontains`. Take a look at this question: http://stackoverflow.com/questions/15465858/django-reverse-to-contains-icontains – ChidG Mar 23 '17 at 07:44

0 Answers0