Seshadri VS
Seshadri VS

Reputation: 550

Django Orm Query - Reverse list lookup

Its easy to check if item is in a list via Django ORM like

User.objects.filter(name__in = ['x', 'y'])

how about reverse way. if User has a field say list of suburbs which he vists (A comma separated list) and we have to check if he has not visited a particular suburb .

class User(models.Model):
    suburb = models.TextField(_('suburbs'),validators=[validate_comma_separated_integer_list], blank=True)

Data when retrieved from shell_plus will be of this sort for

{'suburb': '965,967,969,972' }

Want to get all users who have not visited suburb 100 ?

Upvotes: 0

Views: 324

Answers (3)

aprasanth
aprasanth

Reputation: 1099

Try using exclude with in lookup

User.objects.exclude(suburb__in=['100'])

If your input is {'suburb': '965,967,969,972'},

input = {'suburb': '965,967,969,972' }
input_list = input['suburb'].split(',') # Split the string into list
User.objects.exclude(suburb__in=input_list)

Upvotes: 0

Mohammad Mustaqeem
Mohammad Mustaqeem

Reputation: 1084

You can use contains lookup like

User.objects.exclude(suburb__contains='100')

If you are using postgres db, then I will suggest you use ArrayField instead of comma seprated values.

Upvotes: 0

anupsabraham
anupsabraham

Reputation: 3039

You can achieve this by using Q objects.

startswith_string = str(suburb) + ","
contains_string = "," + str(suburb) + ","
endswith_string = "," + str(suburb)

users = User.objects.filter(
    Q(suburb__startswith=startswith_string) | Q(suburb__contains=contains_string) | Q(suburb__endswith=endswith_string),
)

Upvotes: 2

Related Questions