[Answered ]-Django queryset select where concat

1👍

What you are doing should work, but I would assume vendor_id to be an integer and therefore not have any commas. If this is true your query will always return an empty queryset.

If you want to query vendor_id IN (vendor_id1, vendor_id12, …) then the query is .filter(vendor_id__in=list_of_vendor_ids)

But if your vendor id is indeed a string and can contain commas your query should work but you’ll need to handle edge cases too, such as ‘…,11′, ’11’, and ’11,…’. Therefore I suggest something like this

from django.db.models import Q
vendor_query = Q(vendor_id__iregex=r'^{0},|,{0},|,{0}$|^{0}$'.format(vendor_id))
SysUserPromotionRecord.objects.filter(vendor_query, user_id=102)

Edit: Seeing your changes it looks like the first part of the answer can be ignored.

Edit: Updated the regex as the previous one r',?{},?' would return wrong results for cases like returning 11 while searching for 1

1👍

In mysql queries of the type like '%,1,%' are database killers.

A B-tree index can be used for column comparisons in expressions that
use the =, >, >=, <, <=, or BETWEEN operators. The index also can be
used for LIKE comparisons if the argument to LIKE is a constant string
that does not start with a wildcard character.

The fundamental problem here is that you have not normalized your database. The reason why you shouldn’t store your data like this is explained very well here: Is storing a delimited list in a database column really that bad?
Your first priority is to normalize your database.

As a temporary patch look at the django Concat function.

http://dev.mysql.com/doc/refman/5.7/en/index-btree-hash.html

👤e4c5

Leave a comment